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.