I have a function from which I would like to return a value as a series of events whenever a button is clicked. However, I can’t figure out how to retrieve the value from onreadystatechange. How can I make it so I can return vicArray[vicID]?
function selectVictim()
{
var vicString;
var vicArray;
var vicID;
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();
request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function ()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null )
{
vicString = this.responseText;
vicArray = JSON.parse(vicString);
vicID = Math.floor(Math.random() * (vicArray.length - 1));
}
else alert("Ajax error: No data received");
}
else alert("Ajax Error: " + this.statusText);
}
}
alert(vicArray[vicID]);
}
You can’t. Your
onreadystatechangehandler gets called long after theselectVictimfunction returns.What you have here is, so to say, “asynchronous functions” – i.e. functions that generate their return value not immediately, but after a certain asynchronous process.
To deal with this, one has to use a callback to provide return value:
Note the
callbackargument. Whoever calls this function, must provide another function for this argument. Then note howselectVictimcalls the callback when the return value is ready.Now wherever you call
selectVictim, you must modify your code from:To:
Simple enough?