Implementing Ajax using PHP
 
Published: 23 Jul 2008
Abstract
In this article Babita examines what AJAX is, how it works, and how we can use AJAX with PHP. The article describes the steps required to create an XMLHttpRequest object, request and response procedures along with the required code samples.
by Babita Baliarsingha
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 16008/ 24

Introduction

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. AJAX is not a programming language, but a technique for creating better, faster, and more interactive web applications.

If we are using PHP or any server side technology and need to extract data from storage on a server (e.g. 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 web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from the 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.

Description

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. 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 a response (the response can be in the form of a String or XML).

5. Use the response in your web page.

Create an XMLHttpRequest object

The XMLHttpRequest object is the key to AJAX. Different browsers use different methods to create an XMLHttpRequest object. Internet Explorer uses an ActiveXObject. Other browsers use a built in JavaScript object called XMLHttpRequest. The following code creates an XMLHttpRequest for all browsers.

Listing 1

var aj_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 we are first trying to create an XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject("Msxml2.XMLHTTP"). If that then fails, we will try ActiveXObject("Microsoft.XMLHTTP"). If all these fail, we will alert the user that his/her browser does not support AJAX.

Request for a web page

Now that the XmlHttpRequest object is created, we need to send a web request using the open method.

Listing 2

aj_req.open ("GET", "ajax.php");
aj_req.send(null); 

Here, aj_req is the XMLHttpRequest object. It will request to the server for test.php using the GET method.

Monitor for the response of the request:

In this step we need to check the actual state of the XMLHttpRequest object. We need to change the field value only if the state is complete. For doing this we can assign a function to aj_req.onreadystatechange (here, aj_req is the XMLHttpRequest object), like below.

Listing 3

aj_req.onreadystatechange = handleResponse( );
function handleResponse( ){
if(aj_req.readyState == 4 && aj_req.status == 200){
//returned text from the PHP script
var response = aj_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

Once you take care of catching the readyState, you need to make the actual request using the open() and send() methods. The open method is what we use to set up the request. It takes in a request type (i.e. "post" or "get"), the page URL, and a boolean value indicating whether we are making an asynchronous call or not. In this case we are, so it is true. So to set up the open() call, we use GET, ajax.php for the url, and set the asynchronous boolean to true.

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.

Use the response on your web page

When we get the response back, we have to do something with the data sent back. We use the HandleResponse() function to display the information sent back, when the readyState is 4. The HandleResponse() function should look like the following:

Listing 4

function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}

All this function does is takes the response from the request and puts it in a div on our page. That is all our JavaScript. We need to make our ajax.php file, which is one monstrous file, full of complex code.

Listing 5

<?php
echo "This is a php response to your request!!!!!!";
?>

One echo statement is all we really need for this tutorial. The concept is that all we need to do is send something back to the XMLHTTP object. In the simplest form, this is just some text, where PHP's echo statement works perfectly. This will return our statement back and JavaScript will display it on the page.

Conclusion

Using AJAX from PHP is very easy. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development since 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. 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.

By

Babita Baliarsingha



User Comments

Title: Learn About it   
Name: Php Developer
Date: 2010-06-28 2:01:24 AM
Comment:
This is a nice article, Its using to learn something about it.. Thanks Babita Baliarsingha..,

Do you have a good job.

Thanks a lot..!
Title: nice article   
Name: rupesh
Date: 2008-07-30 2:15:20 AM
Comment:
nicely explained article babita..just keep it up






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 5:52:39 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search