[name=AddClientSubmit] … is the “submit” button on a form.
The $.POST sends the forms data and the post script returns a json response with an error message in it.
If there is no error message I want to return the click function as true so the form is submitted and false if there is an error.
Problem with my script below is javascript doesn’t wait for the $.POST to fully finish and the submitForm value is never set so the form automatically is submitted.
$('[name="addClientSubmit"]').click(function() {
var submitForm = false;
var buttonObj = $(this);
buttonObj.hide();
$.post(
'/jquery/scripts/contacts_clientAddEdit.php',
$('#addClientForm').serialize(),
function(json) {
if(json.error == '') {
submitForm = 'yes';
} else {
jAlert(json.error, 'Error', function() {
buttonObj.show();
});
submitForm = 'no';
}
},
'json'
);
if(submitForm == 'yes') { return true; }
if(submitForm == 'no') { return false; }
});
The problem is that the $.post method is asynchronous so it will return before the submission is complete. There is a way to turn this off but it causes the browser to hang and sometimes behave to the user as if it has crashed.
Instead of creating two separate posts, one for this AJAX functionality and one for the form why not combine them? This will both resolve your issue and result in a quicker response time for the user.