How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.

Here is my JS.

 $('#edit_user_form').bind('click', function (event) {
  event.preventDefault();// using this page stop being refreshing 
   $.ajax({
    data: $(this).serialize(),
    type: $(this).attr('method'),
    url: $(this).attr('action'), 

    success: function () {
     $(".msg-ok").css("display", "block");
     $(".msg-ok-text").html("Profile Updated Successfully!!");
    },
     error: function() {
     //Error Message          
    }  
  });
}); 

PHP

<?php 
require_once 'db_connect.php';
if($_POST) {
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $index_no = $_POST['index_no'];
    $contact = $_POST['contact'];

    $id = $_POST['id'];

    $sql  = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
    if($connect->query($sql) === TRUE) {
        echo "<p>Succcessfully Updated</p>";
    } else {
        echo "Erorr while updating record : ". $connect->error;
    }
    $connect->close();
}
?>

Answers 1

  • ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.

    if you want to handle php error, make following changes in your code

    <?php 
    require_once 'db_connect.php';
    if($_POST) {
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $index_no = $_POST['index_no'];
        $contact = $_POST['contact'];
    
        $id = $_POST['id'];
    
        $sql  = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
        if($connect->query($sql) === TRUE) {
            echo "true";
        } else {
            echo "false";
        }
        $connect->close();
    }
    ?>
    
    
    $('#edit_user_form').bind('click', function (event) {
      event.preventDefault();// using this page stop being refreshing 
       $.ajax({
        data: $(this).serialize(),
        type: $(this).attr('method'),
        url: $(this).attr('action'), 
    
        success: function (res) {
         if(res == 'true') {
              //success code
         } else if(res == 'false') {
              //error code
         }
    
        },
         error: function() {
         //Error Message          
        }  
      });
    }); 
    

Related Articles