Ajax - getting the server's readyState
Didn't find what you want? Try our search
Secondly, we need to write an event handler
which will be called via some event on our user's page, and will handle sending
our request for data to our server.
The event handler will use various methods of our
XMLHTTPRequest object to:
- make the request of the server
- check when the server says that it has completed the request, and
- deal with the information returned by the server
We can make our request of the server by using a GET method to an appropriate
server-side script. Here's an example event handler
called updateData which assumes that we have created our
XMLHTTPRequest object and called
it http:
function updateData(param)
{ var myurl = [here I insert the URL to my server script];
http.open("GET", myurl + "?id=" +
escape(param), true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
Note that the function listens to the
onreadystatechange property of the
XMLHTTPRequest object and, each time this parameter changes,
calls a further function useHttpResponse.
You will note also that, for the sake of clarity, I have said little
about the server-side script which is called - essentially this can be any
server routine which will generate the required output when called with the
relevant URL and appended parameters, as in any other HTTP GET request.
For the sake of the example we are passing a variable named id
with a value param passed as an argument to the
updateData function.
Thirdly, then, we need to write a
function useHttpResponse which will establish when the server
has completed our request, and do something useful with the data it has
returned:
function useHttpResponse() { if (http.readyState
== 4) { var textout =
http.responseText;
document.write.textout; } }
Note here
that our function checks for a readyState value of
4 - there are various numbered states describing the progress
of such a request, but we are only interested in the value of 4, which indicates
that the request is complete and we can use the returned data.
In this case, we have received our information as simple text via the
responseText property of our XMLHTTPRequest
object. Information can, however, be returned as XML or as properties of a
predefined javascript object.
Next: Example Ajax Applications > > >
Before using any software from this site, please see the Terms
|