server side validation for jQuery ajax submission
jquery, php
Solution
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);
}
Problem
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 (e.g. 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; }); ```