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):
- 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.
- 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.
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
- 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.
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
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 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.
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.
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.