I'm trying to set the variable result
but it remains 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
How do I get the object to affect a variable outside of the function it is in? The question is a bit more complex than I had let on. This function is called when a user attempts to submit a form. When true is returned the form should be submitted but if false is returned the form should not be submitted. I now have the 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));
But the form is always submitted, even before "final value..." is displayed. If I add return false at the end of the code then the form is never submitted.