×

Search anything:

Understand AJAX by building a PHP application

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

Reading time: 35 minutes | Coding time: 15 minutes

In this article, we will setup a basic PHP application and demonstrate the working of AJAX. Before going into the demo, we will go through a basic introduction to AJAX.

Introduction to AJAX

AJAX stands for Asynchronous JavaScript and XML. It is a technique for getting or sending data to/ from a server after a webpage has been loaded without loading/ refreshing the entire page. It is used to create better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Javascript.

AJAX is not a programming language. It is a technique for accessing web servers from a web page.

It is data driven as opposed to being page driven. Generally, we make post requests to a webpage and it reloads with the concerned data but with AJAX, this process occurs within the webpage without having to reload it.

ajax

Get started with our PHP demo

First, we need to prepare our system.

You should have PHP server installed on your machine. We will be using XAMPP, which can be downloaded from here. Also, having a text editor like Sublime certainly helps. Even if you don't have one, don't worry, even Notepad will do.

  • Start the Apache server in your XAMPP control panel.

xampp

  • Now navigate to http://localhost/ in your browser.

  • If you see a directory listing of the htdocs folder of your XAMPP installation directory, we're good to go.

  • Now go to the htdocs folder and create a new directory named ajaxtutorial.

PHP

  • Inside the ajaxtutorial directory, create a file named datafile.php with the following contents:
<?php
print "<p>Data displayed here !</p>";
?>

datafile

HTML

We have to create a html file which will do mainly 2 things:

  • have a <button> which when clicked, will make the XML request by calling a function
  • contain a <div> to display information from a server.

Let's name the function to be called by the button getajaxdata(), so the HTML code for the button will look like:

<button onclick=getajaxdata()>Make the AJAX call</button>

The javascript function getajaxdata() needs a parameter id to access the <div> where the data will be displayed, so we need an id attribute for the div.

So, the HTML code for the <div> looks like:

<div id="data" />

The body of the HTML file looks like:

<body>
  <button onclick=getajaxdata()>Make the AJAX call</button>
  <div id="data" />
</body>

Save the file as index.html.

Javascript

Now we need to make the getajaxdata() function:

  • First we need a variable to access the div in the body where data will be displayed.
var display = document.getElementById("data");
  • Next, a variable which acts an object of XMLHttpRequest()
var xmlhttp = new XMLHttpRequest();
  • Now take a close look at the operations we perform with xmlhttp
 xmlhttp.open("GET", "datafile.php");
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlhttp.send();
  • Now we are ready to apply the conditions:
      xmlhttp.onreadystatechange = function() 
      {
        if (this.readyState === 4 && this.status === 200) 
        {
          display.innerHTML = this.responseText;
        } 
        else 
        {
          display.innerHTML = "Getting the data...";
        };
      }
  • In the above code, the if statements contents are the statements which will display the content of the file we opened by using the XMLHttpRequest() object.

  • The else block contains the content which should be displayed while the said task is being performed, just like loading...

  • Now, put this javascript code as a script in the index.html file.

index.html

The index.html file should look like this:

index-1

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
    function getajaxdata(){
      var display = document.getElementById("data");
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "datafile.php");
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() 
      {
        if (this.readyState === 4 && this.status === 200) 
        {
          display.innerHTML = this.responseText;
        } 
        else 
        {
          display.innerHTML = "Getting the data...";
        };
      }
    }
  </script>
</head>
<body>
  <button onclick=getajaxdata()>Make the AJAX call</button>
  <div id="data" />
</body>
</html>

Testing/ Running our application

test1-2

  • Now comes the real test. Click the button that we made and it should display the data that we printed in datafile.php.

test2-1

I hope you got an idea about how ajax works and how it makes the user experience easy and smooth.

When to use AJAX

  • Filtering data: If you've got a large table with a lot of data in it, a nice application for Ajax is to add filters and sorters to the table. Getting your Web table to act more like Excel is really useful to people.

  • Comments: Comments on blogs or even just articles are a great use of Ajax. Comments can change all the time, and especially when a commenter hits the comment button, it's nice to see the comment appear immediately on the page.

  • Form validation: It's so much nicer when the form tells you as you are typing if you've filled it out wrong or not. Having to go to the server and then return an error message is not only old, it's slow. Leave the server validation in the form, that's important for accessibility. But for those who can support Ajax, tell them right away.

When to NOT use AJAX

  • Search engines don't see the data that isn't in the first view(before the ajax call), because they can't access the Ajax.

  • If there's a lot of information involved, it could take a long time to load on a slow connection. And because Ajax doesn't indicate anything is happening it looks like the page is broken.

Understand AJAX by building a PHP application
Share this