I'm trying to validate a form using an AJAX call to check available inventory. If the inventory check has an error it returns a msg, if not the form should submit.
I have the following code:
$("form[id*='distributor_']").submit(function(){
return checkAvailableInventory($(this));
});
function checkAvailableInventory(form) {
$.ajax({
url: "/ajax/quantity.php?" + form.serialize(),
success: function(msg) {
if (msg) {
alert(msg);
return false;
} else {
return true;
}
}
});
}
I suspect that this issue occurs due to the asynchronous nature of AJAX and that the success: clause doesn't fire until well after the checkAvailableInventory() life cycle is completed.
Does anyone have suggestions to solve this issue? I've seen some examples of people using timeouts but that seems like a workaround with possible problems.
One option is to make the call non async. You can set the async
proprety to false. It is true by default. Not sure how long the call is though as it could lock the browser till it completes.
EDIT: Another option is to return false from your method that makes the ajax call. Then in the success method when it reaches there you can unbind the submit functionality from the form and then just call form.submit and it will just post to wherever it would normally without the validation.
you might want to check out the jQuery validate plugin! it's quite simple to use, and handles remote validation very nicely.
the plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ the docs on remote validation: http://docs.jquery.com/Plugins/Validation/Methods/remote#options