It's been a challenge for me to assign a value to the variable result
as it always stays undefined.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText)
{
result = true
alert(xmlhttp.responseText+" here1")
}
else
{
document.getElementById("report").innerHTML = "wrong password/username"
alert(xmlhttp.responseText+" here2")
result = false
}
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name.value));
alert("final value: "+result)
return result//always undefined
Is there a way for an object to impact a variable beyond the function scope? This issue is more intricate than initially thought. The purpose of this function is to be called when a user tries to submit a form. If true is returned, the form should be submitted; if false, the form should not. I now have the following code (thanks sweetamylase).
var result
var checkResult = function(result) {
alert("final value: " + result);
return result
};
xmlhttp.onreadystatechange=function()
{
var result = null;
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText)
{
result = true
alert(xmlhttp.responseText+" here1")
}
else
{
document.getElementById("report").innerHTML = "wrong password/username"
alert(xmlhttp.responseText+" here2")
result = false
}
checkResult(result); // pass result to another function
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name.value));
However, the form is always submitted even before "final value..." appears. If I add return false at the end of the code, then the form never gets submitted.