When the response of an AJAX request is ready on the server, value of the readyState property of XMLHttpRequest object is changed to “4”. This means that the request is now complete and response could be received. onreadystatechange property of the same object stores a user-defined anonymous function which is executed whenever readyState property changes. A typical piece of code for this would be as below:
xmlHttp.onreadystatechange=function () {
if(xmlHttp.readyState==4)
{
//do something with the response
}
};
However, sometimes it is required to pass one or more parameters to this anonymous function. It sounds tricky but it is pretty simple! This anonymous function can not take parameters but it can call another function defined in the same file and pass parameters to it. So, if you want to pass parameters to the anonymous function -you can do it as below:
xmlHttp.onreadystatechange=function () {
stateChanged(parameter1, parameter2);
};
xmlHttp.open("GET", handlingURL, true);
xmlHttp.send(null);
}
function stateChanged(p1, p2)
{
if(xmlHttp.readyState==4)
{
//do something with the response
}
}
Isn’t it pretty clever solution?! It is like taking a bit long route -but this route is not all that difficult -is it? Hope this helps you and save you time. Let me know how you liked this tip. Thank you for using TechWelkin.
Thanks this help me a lot. Ran into one hick-up. Down inside some nest statements is where I was calling this. Values declared outside the last statement, ended up being empty strings in side the callback. Simple fix, just set the parameter to n new variable:
var parameter1 = “Something”;
for (var i =0; i < 100; i++) {
var _parameter1 = parameter1;
xmlHttp.onreadystatechange=function () {
stateChanged(_parameter1, parameter2);
};
xmlHttp.open("GET", handlingURL, true);
xmlHttp.send(null);
}
}
Really Helpful code Man
Thanks A Lot
thank
Thanks you so much, it really worked. :)
thank you dear .. you are great
thank you dear .. you are great
Great solution. That’s exactly i was searching for. Thanks!
Hello ,thanks your AJAX code.
I spend to mauch time to solve this situation BUT …
xmlHttp.onreadystatechange=haberD(bak); DOWS NOT WORK (FUCK OF 2 hour …:)
:)))
You realy helped me. THANKS.
I found yor from google by typing:xmlHttp.onreadystatechange function
THANKS FROM TURKEY …
thank a lot, this coding very use full for me by thiyagarajan