Basic AJAX: Using XMLHttpRequest

May3111May 31, 11

So, XMLHttpRequest is a feature in JavaScript that lets a page make HTTP requests to a web server on the same domain (note: there are ways to make requests to subdomains, they are not covered here).
First, you get an instance of it:
var xhr = new XMLHttpRequest();
You need some way to be notified when the HTTP request is done loading and the data is ready.
It's very similar to the listen() method in chat.botApi.
To listen for the end of the request, you create a function and assign it as the readyState Change Handler:
xhr.onreadystatechange = function() {
// your stuff here
You need to check that the request has ended, cause that function gets called 3 or 4 times depending on the browser, to indicate the various request states (sending, waiting, receiving, done - with done being readyState 4)
So, in your handler, check the readyState:
xhr.onreadystatechange = function() {
if (this.readyState===4) {
// huzzah, the data is here!
Once you have that, you open a connection to the server, with the request type (GET or POST, same as for a <form> action), the URL you want to reach, and Boolean true.
(the last param, true, means asynchronous, which allows the browser and page to do other stuff while the request is loading. It's important, and you should never use false for that value, if you do browser makers will come to your house and change it. And they won't tell you.)
So that part goes like this:"GET", "/path/to/file.html", true);
Finally, you need to submit the request to the server. That part is easy, it only takes one parameter - the POST variables (exactly like <input> fields in a <form>)
if you want to send an HTTP post to your server, for a form or whatever, you need to URL-encode all the parameters and send it as a string
if you're just making a GET request, leave it blank, like so:
... and we're done!

Let me know if this helps you out, or if you would be interested in more articles covering JavaScript basics!

About Jason Miller:

I am a JavaScript developer from Waterloo, Ontario, Canada. When I am not typing green code onto a black screen, you might find me at the nearest coffee pub checking out the brew. I run a internet firm called developIT and maintain blogs and web apps when I can.
Michael Law#
Michael Law#
Lisa Calabrese#
Michael Law#
Scott Jones#
Ann Tabares#
Scott Jones#
Shana Phillips#
Ann Tabares#
Michael Law#
Leave a Comment

Post Comment