Forcing jquery ajax request to wait for response

The first A in AJAX stands for “Asynchonous”. The call is made, and the execution of the function continued without waiting for the call to return.

You could set the async option in your call to false, making your call sychronous. However, you would have to change your functions so the return false makes it through to the check function, and it is not recommended by the jQuery manual:

“The first letter in Ajax stands for “asynchronous,” meaning that the operation occurs in parallel and the order of completion is not guaranteed. The async option to $.ajax() defaults to true, indicating that code execution can continue after the request is made. Setting this option to false (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.”

a better way around it would be to make the checks you can make in “real time” within the function, then start the Ajax request, and submit the form in the success callback of that request.


var name_success = true;

$.ajax({
    type: "POST",
    async: false,
    url: "username.asp",  // Needs to return "EXISTS" in this example 
    data: "username="+theform.username.value,
    success: function(msg){
        username = msg;
        if (username == "EXISTS") {  // Changed callback return value - 
                                     // safer this way
            alert("username already in use");
            name_success = false;   // should work because
                                    // we're in check()'s scope
            return false;
        }
    }
});

alert (name_success);

source: http://stackoverflow.com/questions/2903369/javascript-check-of-a-form-not-waiting-for-ajax-response