views:

3216

answers:

2

Can someone tell me how to return the value of status as the function's return value.

function checkUser() {
    var request;
    var status = false;

    //create xmlhttprequest object here [called request]

    var stu_id = document.getElementById("stu_id").value;
    var dName = document.getElementById("dName").value;
    var fileName = "check_user.php?dName=" + dName + "&stu_id=" + stu_id;
    request.open("GET", fileName, true);
    request.send(null);

    request.onreadystatechange = function() {
     if (request.readyState == 4) {
      var resp = parseInt(request.responseText, 10);
      if(resp === 1) {
       alert("The display name has already been taken.");
       status = false;
      }
      else if(resp === 2) {
       alert("This student ID has already been registered");
       status = false;
      }
      else if(resp === 0) {
       status = true;
      }
     }
    }
    return status;
}

The above function triggers when you hit submit in a registration form (as must be obvious). The problem is, this form submits irrespective of what the response is, and the alert box sometimes shows nothing [blank], sometimes doesn't show at all. However, if I change the ending status to false manually [i.e. replace status with false], the correct value shows up in the alert box.

P.S. I'm worse than a noob in javascript, so suggestions on generally improving the code is also welcome.

+7  A: 

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. Something like this should work:

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

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.

Paolo Bergantino
Thanks a lot for the quick response. Your solution works perfectly. However, I don't understand why setting the value of status from inside the condition doesn't work. Some hint on that would be much appreciated.
Mussnoon
I edited my answer with a more detailed explanation of what is going on. Let me know if it helps. Cheers.
Paolo Bergantino
Thanks a lot. Yes, that helped.
Mussnoon
A: 

It is possible to execute the send method synchronously, so request.responseText will be available immediately, but it's not normally a good idea. The request will hang the browser until it's complete.

To set the request as synchronous, set the third parameter to request.open to "false".

function checkUser() {
    var request;
    var status = false;

    //create xmlhttprequest object here [called request]

    var stu_id = document.getElementById("stu_id").value;
    var dName = document.getElementById("dName").value;
    var fileName = "check_user.php?dName=" + dName + "&stu_id=" + stu_id;
    request.open("GET", fileName, false);
    request.send(null);

    if (request.status === 200) {
        var resp = parseInt(request.responseText, 10);
        if(resp === 1) {
            alert("The display name has already been taken.");
            status = false;
        }
        else if(resp === 2) {
            alert("This student ID has already been registered");
            status = false;
        }
        else if(resp === 0) {
            status = true;
        }
    }
    else {
        alert("Request failed");
        status = false;
    }

    return status;
}

As I mentioned before though, this is not a good idea. It's almost always a better idea to do the request asynchronously so other code can run while you wait for a response. There's a reason Ajax caught on instead of Sjax.

Matthew Crumley