I've found the problem here. I spelled "ReadyState" instead of "readyState". After fixing this, the function fired correctly and picked up the correct value from the server. The problem now is one of returning a value from one javascript function to another. I have confirmed with console.log and alert call debugging that the correct values are being retrieved by the javascript function but for some reason they aren't returned. When I log or alert the values they are all undefined.
Here is the part of the function that calls the second function:
Code:
temp = get_stat("stat1");
document.getElementById('input_1').value = temp;
console.log("Input 1: " + temp);
temp = get_stat("stat2");
document.getElementById('input_2').value = temp;
console.log("Input 2: " + temp);
temp = get_stat("stat3");
document.getElementById('input_3').value = temp;
console.log("Input 3: " + temp);
temp = get_stat("stat4");
document.getElementById('output_1').value = temp;
console.log("Output 1: " + temp);
Here is the get_stat() function:
Code:
function get_stat(stat)
{
var xmlhttp;
var url = "./stat.php?stat=" + stat;
var response;
//Create xmlhttp object
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4)
{
response = (+xmlhttp.responseText);
console.log("Looked up '" + stat +"' parameter from server (value:'" + response + "', type:'" + typeof(response) + "').");
return response;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
Here is a copy of the browser log:
stat1: undefined
stat2: undefined
stat3: undefined
stat4: undefined
Looked up 'stat1' parameter from server (value:'10000', type:'number').
Looked up 'stat2' parameter from server (value:'30.5', type:'number').
Looked up 'stat3' parameter from server (value:'25', type:'number').
Looked up 'stat4' parameter from server (value:'2850', type:'number').
The strange thing here is that the log is picking up the undefined value before the function call. It is as if the function is not firing and just returning undefined and then the function fires at a later point when the response in irrelevant.
This is bizarre, I'd appreciate any help solving this issue.