Getting started with AJAX using PHP : Tutorial

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

tag or 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 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

tags innerHTML. My div tag has the id=’ajax_res’.

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 “Search Result for Status: “.$status.”

“;

$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.

ACTIVE

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

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.

16 Responses to Getting started with AJAX using PHP : Tutorial
  1. […] recorded first by jyaire on 2009-04-16→ Getting started with AJAX using PHP : Tutorial […]

  2. […] public links >> xmlhttp Getting started with AJAX using PHP : Tutorial Saved by canaxis on Wed 15-10-2008 AJAX: Auto Suggest Saved by sylvanne on Mon 13-10-2008 […]

  3. using div
    August 2, 2008 | 11:16 am

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialUsing the DIV Tag with CSS and XHTML+CSSLearn how to use the div tag to create valid XHTML+CSS Web […]

  4. 403
    July 20, 2008 | 2:25 am

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialChurch Happenings – Mercury-Register403-7406 or 403-7043. The Family History Center located at 2390 […]

  5. php httprequest
    July 15, 2008 | 6:59 am

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialDebian — Details of package php-http-request in lennyDownload Source Package php-http-request:. […]

  6. […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialmicrosoft internet explorer 7 and mozilla firefox 2.0 Resources …At the same time, bug tracking […]

  7. tutorial for html table
    July 10, 2008 | 5:06 pm

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialRead “Re: table sorting” at Swing Forum […]

  8. http 500 internal server error
    July 4, 2008 | 6:56 am

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialHTTP Error 500 Internal server error ExplainedIn addition to the 500 error notified back to the […]

  9. […] Ajax Blog: Getting started with AJAX using PHP : Tutorial Opera 8+, and Netscape 7. But the creation of … like 500 Internal Server Error, 400 Bad Request … There is another way of getting the same… […]

  10. data access object
    June 29, 2008 | 11:48 pm

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialNew Version of ArcGIS Explorer Offers Improved Data Compatibility and Better Map Displays PRWeb via […]

  11. the following is not true of xml
    June 29, 2008 | 11:44 pm

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialFeatures and Case Studies ZDNet AustraliaAt NICTA’s recent Techfest conference, researchers from […]

  12. we simplify the internet
    June 29, 2008 | 10:36 pm

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialSDN Communications Selects Infinera to Simplify Business Connectivity in South Dakota Marketwire via […]

  13. form select background image
    June 29, 2008 | 2:05 am

    […] is therefore independent of web server platforms. In this article we will learn about what AJAX ihttp://ajaxblog.com/archives/2008/06/27/getting-started-with-ajax-using-php-tutorialAmes schools map out ambitious technology plan Mid-Iowa NewsWhen Isaac Stahr’s movie is finished, […]

  14. Pages tagged "mozilla"
    June 27, 2008 | 6:50 am

    […] bookmarks tagged mozilla Getting started with AJAX using PHP : Tutorial saved by 3 others     Tdotsweetie bookmarked on 06/27/08 | […]