Hi, i am trying to create a script that uses ajax to validate a username to see if it already exists in a database.
All of my server-side coding works as expected.
I have created the following JavaScript fucntion in order to to obtain information on whether or not the username has been taken:
function ValidateUserName(MyForm){
var UsernameTaken;
// Create XmlHttpObject
var xmlHttp=GetXmlHttpObject();
// Check to see if the "xmlHttp" object was created
if (xmlHttp==null){
// The "xmlHttp" object was NOT created
alert ("Browser does not support HTTP Request");
return;
}
// Set content type
ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
// Build URL and append querystring variables
var url="UsersUpdate.asp";
xmlHttp.open("post",url,true);
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
var UsernameStatus = xmlHttp.responseText;
if(UsernameStatus == "False"){
// Username HAS been taken.
UsernameTaken = true;
}
else{
// Username has NOT been taken.
UsernameTaken = false;
}
// End of If Else Statement.
window.alert(UsernameTaken); // Alert 1
// Alert ouptuts the value of "UsernameTaken" as expected
}
// End of If Statement.
}
// End of function for "xmlHttp.onreadystatechange"
xmlHttp.setRequestHeader("Content-Type", ContentType);
xmlHttp.send("action=ValidateUserName&PotentUsername="+MyForm.Username.value);
window.alert(UsernameTaken); // Alert 2
// Alert ouptuts the value of "UsernameTaken" as "Undefined".
return UsernameTaken;
}
At alert 1 the variable "UsernameTaken" outputs "True" if the username has been TAKEN and outputs "False" if it is NOT taken. So it CAN identify if the username has been taken or not.
However, at alert 2 it outputs the same variable but outputs as "undefined".
The idea is to return "UsernameTaken" so that it can be used by another function to check whether the username has been taken or not.
my understanding WAS that because the handler function on the "onreadystatchange" is within the function then the variables should be local to the "ValidateUserName()" function.
I have also tried declaring a Global variable and using that instead, but the same thing happens.
Any ideas to why this is happening?
Thanks