Home > Articles > Programming > PHP

Applying AJAX to a PHP App to Make It Highly Responsive

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.
Like this article? We recommend

Like this article? We recommend

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

<html>
<head></head>
<body>
   <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"/>
   </form> 
</body>
</html>

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

<?php
   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

<head>
<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; 
         }
      }
   }
   xmlhttp.send(null) 
}
</script>
</head>
<body>
   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>
</body>
</html>

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

<?php
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.

Summary

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020