This is the second tutorial in a series explaining how to implement Ajax “from the ground up”, so if you haven’t yet checked out the first tutorial, then please do so now, as this one will be building on code from part one.
In the first part, we learned how to create an instance of the XMLHttpRequest
object in a cross-browser fashion. In part 2, we’ll discuss the code needed to start communicating with the server. The result of this tutorial will help us send data to the server.
The onreadystatechange
Event Handler
onreadystatechange
is an event handler, much like onclick
and onload
are event handlers. onreadystatechange
is more along the lines of onload
since it is not triggered by user interaction, but by the server.
When we left our code in part one, here’s how it looked (minus the getXhrObject
function which you can get from part one):
var ajaxCapable = getXhrObject(); if (ajaxCapable) { // perform some Ajax functionality here }
The variable ajaxCapable
holds an instance of the XMLHttpRequest
object, which is returned by the getXhrObject
function. The if
statement checks to see if “Ajax is capable”, and then performs some actions. The first line of code we’ll put into our “Ajax capable” section is shown below:
ajaxCapable.onreadystatechange = checkServerResponse;
Right now we’re only concerned with the code to the left of the equals sign. We’ll deal with the right in detail a little later. Every time the server sends the client a status report, the XMLHttpRequest
object updates its readyState
property. This update to the readyState
property triggers the onreadystatechange
event. So that one line of code is, in essence, saying “When the readyState
property changes, run the function called “checkServerResponse”.
That line of code, by itself, will not do anything since we haven’t actually specified any communication with the server. But it’s there and is waiting to execute should that happen. It’s similar to a line like this:
myButton.onclick = popupWindow();
The line above says “when the button is clicked, open the window”. Nothing will happen unless the button is clicked. Likewise, in the previous code, nothing will happen unless the readyState
property is changed — which will only occur when we start the actual communication with the server.
The open
Method
The next line of code will specify the actual file that we’ll be requesting from the server, using a method of the XMLHttpRequest
object called “open”, which takes up to 5 arguments. Here’s how it looks:
ajaxCapable.open("POST", "file-requested.txt", true);
This line of code will not immediately trigger communication with the server. The open
method is merely specifying the details of that communication, which will be triggered a little later. The first argument describes the kind of request being made. In most cases you will be using a POST
or GET
request, although there are a number of other possibilities, which we won’t discuss in detail here.
Generally, if you’re receiving information from the server and you’re not sending any data, then you would use GET
. If you’re sending data to the server, then you would use POST
. However, you can optionally send data via GET
if you append the data in the form of a query string, but the amount of data is limited when using GET
. So only use GET
when sending no information, or when sending a small amount of information. But, as mentioned, the preferred method to send data is by means of POST
, which can also be done via query string values.
The second argument specifies the path to the actual file requested. In this case, we’re assuming the file resides in the same directory as the file that runs the script. But it can optionally use other common path syntax, such as “../file-requested.txt” or “http://www.impressivewebs.com/file-requested.txt”. The first two arguments of the open
method are required.
Finally, the third argument begins the optional arguments. In this case, I’ve only included one of the optional arguments. The one I’ve used here can be either true
or false
and it specifies whether or not the request should be “asynchronous” or not. Since one of the primary reasons to perform Ajax functionality is to utilize the advantages of asynchronous requests, then we would pretty much always be using a value of true
for this argument. Generally, you wouldn’t even specify this argument, as it will default to true
.
The two other optional arguments for the open
method are username and password, but it will be extremely unlikely that you’ll ever have to use those, so we won’t discuss those in any detail here.
The setRequestHeader
Method
Since any page requested by the browser needs to have a series of headers sent along with the request, we will specify those headers, which are metadata elements that describe the type of request, by means of the setRequestHeader
method of the XMLHttpRequest
object.
Here’s how it looks with the two arguments it accepts:
ajaxCapable.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Those two arguments would be appropriate for use with a POST
request, which is the kind of request you will most often be using. So, for our purposes here, we’ll be using POST
, which is the most common type of communication when data is being sent. In our example we won’t be sending any data, but we’ll use POST
regardless.
Further explanation of the setRequestHeader
method can be found on the IE Developer Center as well as on the W3C’s website.
The send
Method
To begin the actual request from the server using the details specified with the open
method, we need to invoke the method of the XMLHttpRequest
object called the send
method. It takes one argument, and looks like this:
ajaxCapable.send(null);
The argument is the data that we want to send to the server. As mentioned, if we’re using GET
then we likely won’t send any data, so the argument is specified as null
. But if we’re using POST
, then we could specify data in the form of a query string, like this:
ajaxCapable.send("id=one&page=about&text=this+is+my+text");
We would ensure that the query string is formatted properly, so this would mean replacing any non-alphanumeric characters with their hex equivalents, as outlined on this page.
Summary
We’ve added 4 lines of code to our Ajax functionality in this tutorial. Here is the complete code (again, minus the getXhrObject
function, for brevity):
var ajaxCapable = getXhrObject(); if (ajaxCapable) { ajaxCapable.onreadystatechange = checkServerResponse; ajaxCapable.open("POST", "file-requested.txt", true); ajaxCapable.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajaxCapable.send(null); }
We’ve completed the code necessary to enable the client to send data to the server, or in some cases to send a request to the server without sending any data along with the request, as we’ve done in our example here.
I hope you’ve enjoyed the progress we’ve made here in part 2, in which we’ve continued to build Ajax functionality “from the ground up”. In part 3, we’ll deal with the checkServerResponse
function, which is a custom function that we will create that will “receive” the response from the server and then perform actions accordingly.
Recall from the code above that the checkServerResponse
function will be triggered every time the readyState
property of the XMLHttpRequest
object is changed (i.e. when the onreadystatechange
event is triggered). So our next part will deal specifically with code that will be placed inside of that custom function.
Download the complete code from parts 1 and 2, or view a demo using the buttons below.
This is great men! coding and visualy is great! keep on doing this nice understandable tutorials!
Are you ever going to make Ajax From the Ground Up: Part 3?
Yes, I do plan to finish this series, however Ajax with raw JS is not a very popular topic, so the incentive to continue writing about this was minimal.
Thanks for finishing the 3rd. =)