1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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

2 Comments

Thanks for the suggestion. Just don't need it.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.