tags:

views:

37

answers:

2

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.

+1  A: 

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.

spinon
OMG! So easy. I can't believe that I didn't think about that before. It worked perfectly. Thank you!
gurun8
No problem. Glad to help. Which option did you end up going with out of curiosity?
spinon
A: 

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

Patricia
Thanks for the suggestion. Just don't need it.
gurun8
no worries! i hope you didn't go with the async = false. this will lock up your clients browser for the duration of the ajax call, and that is never a good thing! the solution in the edit seems ok though.
Patricia