AJAX: Passing Parameters To onreadystatechange Function

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.

9 thoughts on “AJAX: Passing Parameters To onreadystatechange Function”

  1. 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);
    }
    }

  2. 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 Comment

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