AJAX: Passing Parameters To onreadystatechange Function

In AJAX paradigm, onreadystatechange function of xmlHttp object does not accept any parameters. Learn how you can make this function do what you want.

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
        }
}

It is like taking a 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. Cheers!

Comments

  1. Ercan says

    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 …

Leave a Reply

Your email address will not be published. Required fields are marked *