Home > Articles > Programming > PHP

Applying AJAX to a PHP App to Make It Highly Responsive

  • Print
  • + Share This
AJAX is rapidly becoming an integral part of websites. It not only provides better interactivity but also reloads the dynamic content of web pages quicker than traditional web pages. Learn to apply AJAX in PHP applications to enhance interaction between the user and application.
From the author of

Ajax stands for Asynchronous JavaScript and XML. Usually in a traditional web application, when some data is accessed from the database on the server, an HTTP request from the client is made to the server either using GET or POST method. After receiving the data from the server, the web page needs to be reloaded entirely to display the fetched data. In AJAX technology, the data from the server can be accessed in the background and can even be displayed on the page without a reload.

With AJAX, JavaScript communicates directly with the server through the JavaScript XMLHttpRequest object (XML over HTTP) and it is with the help of this object that a web page can make a request to, and get a response from, a web server without reloading the page.

A traditional web page takes a longer time to get the desired results because of the round trip; that is, all the information entered by the user on the page is sent from the client to the web server. The web server processes the data and the desired information is sent back to the client. Even if small changes are required in the page, the entire page is refreshed. In a traditional web application, we don’t have a facility to refresh only a small portion of the web page; instead the complete page is refreshed, which is very time-consuming.

To understanding how Ajax is applied on a PHP app, we will first make a simple traditional PHP program. To that PHP program, we will apply AJAX to see its impact or benefit, that is, how AJAX makes it highly responsive. You can download sample code to make it easier to follow along.

We will make a simple PHP program that will prompt the user to enter a name and an email address. After entering a name and an email address, when the Submit key is pressed, the user is navigated from the current web page to another page, which in turn displays a welcome message along with the user’s name.

Listing 1 shows a simpleform.php that prompts the user to enter a name and an email address. On occurrence of an event, the data entered by the user passes to another PHP script for processing. Clicking a button is the most commonly used event.

Listing 1: Code in the simpleform.php file

   <form action="display.php" method="get">
      Enter your name: <input type="text" name="user_name" /><br>
      Enter your email id : <input type="text" name="email_id" ><br>
      <input type="submit" value="Submit"/>

The above form displays two input boxes named “user_name” and “email_id”. The form “action” points to a php file, “display.php” and the HTTP “method” used is “Get”. The contents of the form will be submitted to php script, “display.php”, using the HTTP request-method, GET, for further processing.

Remember, the information is passed from one PHP script to another using either of the two HTTP Request methods, GET and POST. Sending data through the GET method is easier but less secure because it is displayed in the browser's address bar. Also, there is a limit on the size of the data that can be passed through the Get method.

Listing 2 shows the code of display.php file that accesses the username and email address sent from the simpleform.php page and displays them along with a welcome message.

Listing 2: Code in the display.php file

   echo "Welcome " . $_GET['user_name'] . "<br>" ;
   echo "Your email id is  " . $_GET['email_id'] ;

In the above PHP script, the $_GET array is used to fetch the data sent from the simpleform.PHP page. Basically, the $_GET is an array where data sent from the previous page through HTTP GET method is stored. The data from the previous page is sent in pairs, variable name(s) and its value(s). ON running the simpleform.php, the user is prompted to enter the name and email address (see Figure 1 [left]). After entering the required information, when the user clicks the Submit button, navigation takes place from simpleform.php to display.php page. The display.php accesses the user_name and email_id sent from the simpleform.php script through the $_GET array and displays them along with the welcome message (see Figure 1 [right]).

Figure 1 The user is prompted to enter the name and email address. (right) Navigated to another PHP web page showing the welcome message along with the user’s name

With AJAX all the above limitations of traditional web applications are removed because it consists of the following components (see Figure 2):

  • XmlHttpRequest
  • JavaScript
  • DOM (Document Object Model)
  • CSS (Cascading Style Sheets)

Figure 2 AJAX web application model

XmlHttpRequest: It is this object that communicates with the server asynchronously, meaning it allows the browser to talk to the server without requiring a postback of the entire web page. Modern web browsers (Chrome, Firefox, IE7+, Opera, and Safari) include a native XMLHttpRequest object for implementing AJAX, whereas in Internet Explorer, an XmlHttpRequest object is provided by the MSXML ActiveX component.

JavaScript: Ajax applications use JavaScript code for the following reasons:

  • It is a scripting language that is interpreted.
  • The syntax of commands is easier to learn.
  • It can automate several tasks like validation of userid, email id, and so on.

DOM (Document Object Model): It provides a tree-like structure to a web page as a set of programmable objects, which can be manipulated using JavaScript code. It allows dynamic updating of even a part of a web page.

CSS (Cascading Style Sheets): It is a centralized way of defining all the styles to be applied to different elements of a web page at one place. It makes web applications appear more consistent and attractive. CSS styles are implemented by defining style rules in a separate document, which is then referred to by the web page where styles have to be applied.

The XMLHttpRequest plays a major role in performing an asynchronous request in the Ajax web application model (refer to Figure 1). The client makes an XMLHTTPRequest object to communicate with the web server (fetching data from the server without postback). The client may use

  • JavaScript to automate validation or navigation tasks
  • CSS for applying styles uniformly
  • DOM to update a part of the web page

The web server searches for the desired data from the database, and the fetched data (it may constitute a part of the whole page) is sent back to the client to update a portion of the web page without delay.

Conclusion: Ajax applications make use of an XmlHttpRequest object for communicating with the server asynchronously, that is, while the user is still working on the page. Also, only the desired data is fetched from the server and not the entire web page. On the clientside, JavaScript plays a major role as it processes the server’s response and modifies the web page through its DOM to specify that action is completed. Optional CSS provides a consistent look and feel to the web application.

To apply AJAX on the simpleform.php (refer to Listing 1), create a copy of simpleform.php file, rename it to ajaxform.php, and modify its code to appear as shown in Listing 3.

Listing 3: Code in the ajaxform.php file

<script language="JavaScript" type="text/JavaScript">
function makeRequestObject(){
   var xmlhttp=false; 
   try {
      xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
   } catch (e) {
      try {
         xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); 
      } catch (E) {
         xmlhttp = false;
   if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
      xmlhttp = new XMLHttpRequest(); 
   return xmlhttp;

function showdata()
   var xmlhttp=makeRequestObject();
   var user=document.getElementById('user_name').value;
   var email=document.getElementById('email_id').value;
   var file = 'ajaxaccessdata.php?usernme='; 
   xmlhttp.open('GET', file + user+'&emailid='+email, true); 
   xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status == 200) { 
         var content = xmlhttp.responseText; 
         if( content ){ 
            document.getElementById('info').innerHTML = content; 
   Enter your Name: <input type="text" id="user_name"/> <br>
   Enter your email id : <input type="text" id="email_id" ><br>
   <input type="button" onclick="showdata()" value="Submit" ><br><br>
   <div id="info"></div>

First, the <body> section of the web page is executed that prompts the user to enter a username and an email id. The data entered is then assigned to the variables, user_name and email_id, respectively. The code ensures that when the Submit button is clicked, the JavaScript method, showdata(), is invoked. Finally, a div element with id, info is defined for displaying the response or result sent by the server.

In the showdata() method, an XMLHttpRequest object is created by invoking the makeRequestObject() function. Following are the steps involved in performing an asynchronous request to the server:

  • Create an XMLHttpRequest object.
  • Request data from the server using the XMLHttpRequest object.
  • Monitor the change in state of the request.
  • If the request is successful, retrieve data from the response stream.
  • Apply the response received from the server in the web page.

The XMLHttpRequest object is implemented by Microsoft as an ActiveX object in Internet Explorer and is supported by most of its versions. In some browsers, XMLHttpRequest is a native object whereas in Internet Explorer, the XMLHttpRequest is implemented as an ActiveX control; hence the process of creating XMLHttpRequest instance varies for each browser.

The makeRequestObject() function is called to create the XMLHttpRequest object. First, we try to create an XMLHttpRequest object by invoking the ActiveXObject("Msxml2.XMLHTTP") method assuming that the browser is IE6+. If the method fails, the ActiveXObject("Microsoft.XMLHTTP") method is invoked assuming the browser is IE5.x. If both the methods fail, the built-in JavaScript function, XMLHttpRequest(), is called to create the XMLHttpRequest object.

The showdata() method accesses the name and email address entered by the user in the textboxes named user_name and email_id (in the <body> section) and assigns the values to the variables, user and email, respectively.

After successful creation of XMLHttpRequest object, the next task begins, that is, requesting data from the server. Using the XMLHttpRequest object, a web request is sent to fetch data from the server. The request is made by invoking the open method with the syntax as shown below:

XMLHttpRequest object.open(HTTP request method, filename to execute, boolean)

  • HTTP request method: It may be GET, POST, or any other method that is supported by the server.
  • Filename: It is the URL of the file (residing on the server) that we want to invoke to fetch the desired information from the server.
  • Boolean: It is the optional parameter to specify whether the request is asynchronous. If this parameter is set to true, it means the request is asynchronous; that is, the execution of the JavaScript function will continue without waiting for the server’s response.

In the above code (Listing 3), we use the open method that makes a request to the server through the GET method, asking to execute the file ajaxaccessdata.php. The username and email address are passed to this file to perform processing on them.

Because an asynchronous request is made to the server, we need to watch for the state of the request and the response generated by the server for the request. For doing so, we take the help of the event handler, onreadystatechange, which fires at every state change. So, whenever the state of the request changes, the function() is executed where the value of the readyState property is checked (to see if it has become 4, meaning the request is complete, that is, the full server response is received). Also the status of the HTTP request is checked to see if its value is 200, which means no error occurred in the processing of the request.

The response is then retrieved from the response stream in the form of text (it can also be in XML and JSON format) and is assigned to the variable, content.

Then, the element with id, info, is searched for in the document (web page) and its innerHTML property (the property used to display results) is assigned the server response. That is, ajaxaccessdata.phpfile is executed on the server, and its result or output is displayed in the current web page, ajaxform.php by setting innerHTML property of div element of id, info.

As said earlier, the response generated by the server is based on the execution of the file ajaxaccessdata.php (see Listing 4).

Listing 4: Code in the ajaxaccessdata.php file

echo "Welcome " . $_GET['usernme'] . "<br>" ;
echo "Your email id is  " . $_GET['emailid'] ;

Let’s analyze what it returns. The file returns two lines of text to the client: "Welcome" along with the name of the user and "Your email id is  ". The name and email id of the user are retrieved from $_GET array.

On running the PHP program, the ajaxaccessdata.php user will be prompted to enter the name and email address (see Figure 3 [left]). After entering the name and email address, when the user clicks the Submit button, the welcome message along with the username displays on the same page (see Figure 3 [right]).

Figure 3 (left) The user is prompted to enter the name and email address. (right) The welcome message along with the user’s name appears on the same page by implementing AJAX

Hence the output appears quite faster because neither navigation took place (which happens in traditional web applications) nor the entire web page was required to be reloaded but only one element of the page.


You've learned how to make a PHP to quickly response to the user actions. You saw the role of JavaScript and XMLHttpRequest object in performing asynchronous communication with the web server.

You also saw that unlike traditional web applications, where the entire web page is reloaded on the occurrence of an event, through AJAX, we can update even a small portion of the web page.

For more interesting programs, check out my book Android Programming Unleashed. The book uses a step-by-step approach to explore the features of this amazing smartphone platform.

  • + Share This
  • 🔖 Save To Your Account