Home > database >  Form is not displaying errors if ajax is used
Form is not displaying errors if ajax is used

Time:01-24

I'm checking this form for errors using PHP code which is on the same index.php file:

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">

                        <?php if(!empty($formErrors)){  ?>
                            <div id="errors">    
                                <?php 
                                    foreach($formErrors as $error)
                                        { echo '* ' . $error . '.<br/>';}
                                ?>
                            </div>
                       <?php } ?>

<input type="text" name="firstname">
<input type="submit" value="send">
</form>

The PHP code is as follows:

<?php 
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

         $fname = $_POST['firstname'];
         $formErrors = array();

            if(strlen($fname) < 2 ){
                $formErrors[] = "First name must be longer than 1 character";
            }
}
?>

Everything is working fine up to this point, except that I want to prevent the page from scrolling to the top upon form submission. Therefore i used ajax to solve this problem:

$("form").submit(function(e){
    e.preventDefault();
    $.ajax({
      type: $(this).attr("method"),
      url: $(this).attr("action"),
      data: $(this).serialize()
    });
  });

Now the form errors won't display anymore, which is not what I want. How can I show the errors again while not discarding ajax? Thanks.

CodePudding user response:

Although this isn't the best way, you can echo the JSON from the file and display those errors in your ajax function like below:

FrontEnd(ajax):

$("form").submit(function(e){
    e.preventDefault();
    $.ajax({
      type: $(this).attr("method"),
      url: $(this).attr("action"),
      data: $(this).serialize()   '&ajax=1',
      dataType:'json',
      success: function(res){
        if(res.success === false){
           $('#errors').html('<ul><li>'   res.errors.join('</li><li>')   '</li></ul>');
        }else{
           $('#errors').html('');   
        }
      } 
    });
  });

Backend:

<?php 
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

         $fname = $_POST['firstname'];
         $formErrors = array();

            if(strlen($fname) < 2 ){
                $formErrors[] = "First name must be longer than 1 character";
            }
        // add this additional check 
        if(($_POST['ajax'] ?? 'N/A') == '1'){
            echo json_encode(['success' => false,'errors' => $formErrors]);
            exit; // since we will only send the JSON back to the browser, not the entire form
        } 
}
?>

Change your form code to this(adding a errors div always by default):

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
    <div id="errors"></div>
    <input type="text" name="firstname">
    <input type="submit" value="send">
</form>
  •  Tags:  
  • Related