Return value from function with an Ajax call [duplicate]

The problem is that onreadystatechange won’t fire until… wait for it… the state changes. So when you return status; most of the time status will not have had time to set. What you need to do is return false; always and inside the onreadystatechange determine whether you want to proceed or not. If you do, then you submit the form. In short, take the code that handles the return value and instead run it from within the readystatechange handler. You can do this directly:

request.onreadystatechange = function() {
    if (request.readyState == 4) {
        var resp = parseInt(request.responseText, 10);
        switch (resp) {
        case 0:
            document.getElementById('myform').submit();
            break;
        case 1:
            alert("The display name has already been taken.");
            break;
        case 2:
            alert("This student ID has already been registered");
            break;
        }
    }
}
return false; // always return false initially

or by passing a continuation to the function that makes the asynchronous call:

function checkUser(success, fail) {
    ...
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var resp = parseInt(request.responseText, 10);
            switch (resp) {
            case 0:
                success(request.responseText);
            case 1:
                fail("The display name has already been taken.", request.reponseText);
                break;
            case 2:
                fail("This student ID has already been registered", request.reponseText);
                break;
            default:
                fail("Unrecognized resonse: "+resp, request.reponseText);
                break;
            }
        }
    }

In addition to this, before the default return false; you might want to have some sort of indicator that something is going on, perhaps disable the submit field, show a loading circle, etc. Otherwise users might get confused if it is taking a long time to fetch the data.

Further explanation

Alright, so the reason your way didn’t work is mostly in this line:

request.onreadystatechange = function() {

What that is doing is saying that when the onreadystatechange of the AJAX request changes, the anonymous function you are defining will run. This code is NOT being executed right away. It is waiting for an event to happen. This is an asynchronous process, so at the end of the function definition javascript will keep going, and if the state has not changed by the time it gets to return status; the variable status will obviously not have had time to set and your script would not work as expected. The solution in this case is to always return false; and then when the event fires (ie, the server responded with the PHP’s script output) you can then determine the status and submit the form if everything is a-ok.

Leave a Comment