Sending the Server Request
Lesson 8, "The XMLHTPPRequest Object," discussed at some length the JavaScript XMLHTTPRequest object and how an instance of it may be created in various different browsers.
Now that we have our XMLHTTPRequest object, let's consider how to create and send server requests, and what messages we might expect to receive back from the server.
We're going to jump right in and first write some code using what you learned in Lesson 8 to create an XMLHTTPRequest object called myRequest. We'll then write a JavaScript function called callAjax() to send an asynchronous request to the server using that object. Afterward we'll break down the code line by line to see what it's doing.
Listing 9.1 shows our prototype function to prepare and send an Ajax request using this object.
Listing 9.1. Sending a Server Request
function getXMLHTTPRequest() |
Tip
![]() | Lines starting with // are treated as comments by JavaScript. You may use lines like these to document your code or add other useful notes, and your browser's JavaScript interpreter will ignore them when executing code instructions. |
First, we need to create an instance of an XMLHTTPRequest object and call it myRequest. You'll no doubt recognize the code for this from Lesson 8.
Next we'll look at the function callAjax().
The first line simply declares a variable and assigns a value to it:
var lastname = 'Smith';
This is the piece of data that our function intends to send to the server, as the value of a variable called surname that is required by our server-side script. In reality, of course, the value of such data would usually be obtained dynamically by handling a page event such as a mouse click or a keyboard entry, but for now this will serve as a simple example.
The server request we intend to make is a GET request, so we must construct a suitable target URL having our parameter and value pairs suitably coded on the end; the next line carries this out:
var url = "myserverscript.php?surname=" + lastname;
We dealt briefly with the open() method in Lesson 8. We use it in the next line to prepare our server request:
myRequest.open("GET", url, true);
This line specifies that we are preparing a GET request and passes to it the destination URL complete with the appended content of the GET request.
The third parameter, TRue, indicates that we want our request to be handled asynchronously. In this case it could have been omitted because the default value of TRue is assumed in such cases. However, it does no harm to include it for clarity.
Next, we need to tell our XMLHTTPRequest object myRequest what it should do with the "progress reports" it will receive from the server. The XMLHTTPRequest object has a property onreadystatechange that contains information about what JavaScript function should be called whenever the server status changes, and in the next line
myRequest.onreadystatechange = responseAjax;
we assign the function responseAjax() to do this job. We will write this function later in the lesson.
Dealing with the Browser Cache
All browsers maintain a so-called cache of visited web pages, a local record of page contents stored on the hard disk of the browser's computer. When you request a particular web page, the browser first tries to load the page from its cache, rather than submitting a new HTTP request.
Note
![]() | This appears to be more of a problem with IE than with the non-Microsoft browsers. Only GET requests are affected; POST requests are not cached. |
Although this can sometimes be advantageous in terms of page load times, it creates a difficulty when trying to write Ajax applications. Ajax is all about talking to the server, not reloading information from cache; so when you make an asynchronous request to the server, a new HTTP request must be generated every time.
It is possible to add HTTP headers to the data returned by server-side routines, intended to tell the browser not to cache a particular page. Examples include
"Pragma: no-cache"
and
"Cache-Control: must-revalidate"
among others.
Unfortunately such strategies vary widely in their effectiveness. Different browsers have different cache handling strategies and support different header declarations, making it difficult to ensure that pages are not cached.
A commonly used trick to work around this problem involves the adding of a parameter with a random and meaningless value to the request data. In the case of a GET request, this necessitates adding a further parameter and value pair to the end of the URL.
If the random part of the URL is different each time, this effectively "fools" the browser into believing that it is to send the asynchronous request to an address not previously visited. This results in a new HTTP request being sent on every occasion.
Let's see how to achieve this. In JavaScript, you can generate random numbers using the Math.random() method of the native Math() object. Listing 9.2 contains a couple of changes to our callAjax() function.
Listing 9.2. Dealing with the Browser Cache
function getXMLHTTPRequest() |
We can see from Listing 9.2 that the script will now generate a destination URL for our Ajax request that looks something like this:
myserverscript.php?surname=Smith&rand=XXXX
where XXXX will be some random number, thereby preventing the page from being returned from cache and forcing a new HTTP request to be sent to the server.
Note
![]() | Some programmers prefer to add the current timestamp rather than a random number. This is a string of characters derived from the current date and time. In the following example, the JavaScript Date() and getTime() methods of the native Date() object are used: myRand= + new Date().getTime(); |