AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.
In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.
If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.
1. Create an XMLHttpRequest object.
2. Then using this object, request data from the server.
3. JavaScript will then monitor for the changing of state of the request.
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).
5. Use the response in your web page.
1. Create an XMLHttpRequest object
JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5
req = new ActiveXObject(“Microsoft.XMLHTTP”);
} else if(window.ActiveXObject){
//For IE 6+
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(“Microsoft.XMLHTTP”) and for IE 6.0+ use new ActiveXObject(“Msxml2.XMLHTTP”). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.
var req;
try
{
// Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
}
}
In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(“Msxml2.XMLHTTP”), and if it fails also we will try ActiveXObject(“Microsoft.XMLHTTP”). If all these fail, then we will alert the user that his/her browser does not support AJAX.
2. Request for a web page
After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.
req.open(“GET”,”somedata.php”);
req.send(null);
Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :
req.open(“GET”,”somedata.php”,true);
req.send(null);
Both of the above is correct.
3. Monitor for the response of the request
You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.
req.onreadystatechange=function()
{
if(req.readyState==4 && req.status == 200)
{
var resp = req.responseText;
}
}
Or like this,
req.onreadystatechange = handleResponse;
function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}
The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.
4. Get the response
The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.
5. Use the response on your web page
You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a <div></div> tag or <span></span> tag (See below for the implementation of this)
Using AJAX with PHP
I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}
}
Now I add a <script></script> tag in my PHP pages like following to access the JavaScript functions.
Then I create a function called sendReq() as shown above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a <div> tags innerHTML. My div tag has the id=’ajax_res’.
<div align=”center” class=”black” id=”ajax_res”>
<img src=”wt_bg.jpg”>
</div>
After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.
My get_lcm.php looks like this.
<?php
include_once(“create_table.php”);
if(!empty($status)){
echo “<strong>Search Result for Status: “.$status.”</strong><br><br>”;
$ct = new createtable(“select * from lcm where state=$status”);
$ct->table_viewer();
}
?>
I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.
I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.
<a class=”none” href=”#” onClick=”sendReq(1)”>ACTIVE</a>
If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the <div> tag.
Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.
There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.