&security


The Callback Function

 

Having instantiated our XMLHTTPRequest object (see here) we can then send our Ajax request. Let's suppose our JavaScript function called from the page is called ajaxcall, and requires one argument thedata:

        var url = 'serverscript.php?data=';
        function ajaxcall(thedata) {
        http.open("GET", url + escape(thedata), true);
        http.onreadystatechange = handleHttpResponse;
        http.send(null);
        }

In this case we are making a GET call (XMLHTTPRequest supports POST too). The second parameter of the open method contains the address of the server-side function to be called (in this case the data has been added as a GET parameter), and the third parameter determines whether we want the call to be asynchronous (if we choose true, the call will be asynchronous and will happen in the background, while we continue to crowse the page; if false, operation will halt until the server script completes its processing).

 

In the following line, we pass the name of our JavaScript function that is to process the returned data (here handleHttpResponse).

 

Finally we send the request using send().

 

Now let's look at handleHttpResponse(). This is known as the callback function.

        function handleHttpResponse() {
        if (http.readyState == 4) {
            var data_returned = http.responseText;
              //  ... we can process this however we please ...
           }
        }

See also the tutorial on displaying a 'please wait' graphic, which follows logically from the above code.



This site is brand new and so still somewhat under construction.

Why not bookmark it and call back regularly?

Sponsored Links:

Links: