With modern websites it is important to decrease loading times as much as possible, one such method is to make use of asynchronous Javascript and XML (AJAX) development techniques, the purpose of which is to request information from the server without having to refresh the page.
The desired information from the server could be in the form of HTML documents- in which case it will return the contents, or it could be a PHP script which will return whatever it prints out. AJAX is not limited to only these two types of files, but these are usually the most relevant.
Javascript by default offers the XMLHttpRequest class. Another option that exists is to use jQuery's AJAX methods, this requires the developer to download and include the jQuery package as it is not installed by default.
Here we will be using Javascript's XMLHttpRequest class to perform AJAX operations.
Creating and sending a request using XMLHttpRequest
When using XMLHttpRequest, there are several important components to remember, the first is create a new XMLHttpRequest object and assign it to a variable.
var xmlHttpObject = new XMLHttpRequest();
the XMLHttpRequest object has 2 methods you will need to call to send a request to the server.
The first method that needs to be called is open(). This method initializes a new request and allows you to specify the request type (POST or GET), the URL of the file you are requesting, and whether or not the request should be asynchronous (this will usually be true).
xmlHttpObject.open( method, URL, async );
Once you've initialized your request using open() you can make use of the send() method to actually send the request to the server:
xmlHttpObject.send();
The send method has an optional argument for a string that is sent along with the request. This string argument is used when making use of the POST method as you can only include a query string in the URL argument of the open() method when making use of the GET method.
xmlHttpObject.send( "param1=arg1¶m2=arg2" );
Now let's put these methods together to send a basic GET request to the server for the file "test.php"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open( "GET", "test.php", true );
xmlHttpObject.send();
This will not return a value that you can use in Javascript, for that you'll need a request response handling function (see below), however these 3 components alone can be useful for sending data to your server when you do not require a response.
Fetching a response from the server in Javascript
To fetch a response from the server you'll need to create a function that is called every time the "ready state" of the request changes, once is has reached the point where the request is complete and a response is ready, then we can fetch the response and use it for processing in Javascript.
The first step here is to create the function that listens for a change in the request's state, we can do this using onreadystatechange which is accepts a function.
xmlHttpObject.onreadystatechange = function() {
}
Next we need to check that the readyState attribute of the object is 4 (which means it is completed and contains a response) and that the status attribute is 200 (which means the URL of the request was found and accessed). For this we'll use a simple if statement within our function:
if ( xmlHttpObject.readyState === 4 && xmlHttpObject.status === 200 ) {
}
When you've confirmed the state of the request, you can fetch the response using the responseText attribute:
var response = xmlHttpObject.responseText;
Putting it all together:
xmlHttpObject.onreadystatechange = function() {
if ( xmlHttpObject.readyState === 4 && xmlHttpObject.status === 200 ) {
var response = xmlHttpObject.responseText;
}
}
This function should be placed before initializing and sending your request.
This code will send a request to the server for the file "testScript.php",
it will then fetch the response and create an alert containing that response.
Javascript:
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.onreadystatechange = function() {
if ( xmlHttpObject.readyState === 4 && xmlHttpObject.status === 200 ) {
var response = xmlHttpObject.responseText;
alert( response );
}
}
xmlHttpObject.open( "GET", "testScript.php", true );
xmlHttpObject.send();
testScript.php:
<?php
echo( "hello world" );
?>
This will create an alert with the text "hello world"
Important things to note:
-Any processing that is only meant to happen after the request must be done so within the if statement of the onreadystatechange function as the request may take anywhere from milliseconds to seconds to complete, so any processing that relies on the response must not be done before the request is complete.
-Issues concerning the request can usually be debugged within your browser's developer section within the network tab. This will shows all requests to the server including status, headers and responses (see
).