Javascript Object Properties go to undefined after ajax request returns
- by adasdas
if you have an object and set a property for it, you can access that property in a function called on that object. but if you call a function and do an ajax request such that a different function is called from onreadystatechange, that secondary response function does not have access to the property. Thats a little confusing so see what I mean here. The property this.name is the one that changes.
//from W3Schools website
function getXHR(){if (window.XMLHttpRequest){return new XMLHttpRequest();}if (window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP");}return null;}
function TestObject()
{
this.name = ""; //public
var xhr = null; //private
var response = function() //private
{
if(xhr.readyState > 3)
{
alert("B: my name is " + this.name);
}
}
this.send = function() //public
{
alert("A: my name is " + this.name);
if(xhr === null)
{
xhr = getXHR();
}
var url = "http://google.com";
xhr.onreadystatechange = response;
xhr.open("GET", url, true);
xhr.send(null);
}
}
var o = new TestObject();
o.name = "Ice Cube";
o.send();
Results are:
A: my name is IceCube
B: my name is undefined
If response is public this happens as well. If xhr is public this also happens. Something occurs so that the response function called doesnt have access to the same parameters.