For some reason I always receive undefined if I return the value but if I’m trying to display it in alert I receive the php values.
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch(e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
//Browser does not support AJAX
return false;
}
}
}
return xmlHttp;
}
function isUsernameExists() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
handleResponse(xmlHttp.responseText);
}
}
var str = document.getElementById('username').value.toString();
xmlHttp.open("GET", "ajax.php?username="+str, true);
xmlHttp.send(null);
}
Edit:
function handleResponse(response) {
return response.toString();
}
Thanks,
Guy Dor
It looks like you are trying to read the return value from this function:
It doesn’t have a
returnstatement, so it will always beundefined.I’m guessing you expect this return statement to pass the value you want:
But that is part of this function:
Which is called automatically when the readystatechange event fires, and not by any function call you make.
Asynchronous JavaScript and XML rarely uses XML but is asynchronous. Anything you want to do with the data fetched needs to be done by the callback function you assign to onreadystatechange. It can call other functions, but it cannot return anything (at least not that will be received anywhere useful).