Javascript Object Properties go to undefined after ajax request returns
Posted
by adasdas
on Stack Overflow
See other posts from Stack Overflow
or by adasdas
Published on 2010-06-17T16:48:41Z
Indexed on
2010/06/17
16:53 UTC
Read the original article
Hit count: 222
JavaScript
|AJAX
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.
© Stack Overflow or respective owner