简体   繁体   中英

server side validation for jQuery ajax submission

I am using jQuery ajax to submit a form. I have written php code in a different file to insert the form-data into a database table. How can I do the server side validation and show corresponding error message (eg this field cannot be empty)? I have no idea about how to solve this problem. jQuery function that does the submission is as follows

$('#form-add-button').click(function () {
   $.ajax({
      type: "POST",
      url: 'addemployee.php',
      data: $("#employee-form").serialize(),
      success: function (response) {
          showEmployeesData();
          initInputValues();
      },
      error: function (response) {
          alert('Error:' + response);
      }
  });
  return false;
});

Before inserting the data into the database validate the data using php if you have errors in validation you can encode the error message as json and return back to the ajax function and show the message

AJAX FUNCTION

$.ajax({
    type: 'post',
    url: 'lettersubscribe/subscribe',
    dataType: 'html',
    data:$("#subscribenewsletter").serialize(),
    success: function (html) {
        var result = jQuery.parseJSON(html);
        if(result.success == true){
            $("#subscribeBox").html('<span id="blacktext">TACK / THANKS FOR</span><span id="bluetext"> SIGNING UP!</span>');
        }else{
            $("#subscribe_result").html(result.error);
        }
    }
});

//PHP FUNCTION
function subscribe(){

    $msg = array();
    $msg['success'] = TRUE;

    if($_POST['emailid']){
        // Validate email id
    }else{
        $msg['email'] ="Invalid Email";
        $msg['success'] = false;
    }

    echo json_encode($msg);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM