Easy Ajax Example Using jQuery

October 21, 2016

This is an easy example of doing basic Ajax with jQuery. This example is short and sweet.

Only two files are needed. First, you're going to need index.html, a basic page that will perform the Ajax request. Then, you're going to need ajax.php that handles the dynamic Ajax request on the server side and responds with a string containing a random number. Save these files off to a folder accessible through your favorite web server capable of rendering PHP.

index.html

This page contains several elements with individual ids. The key here is they all have the class dynamic which is used to select each dynamic value in the jQuery example. Every second, it will loop through each of the dynamic elements, make a request to the server, and then populate the contents of each of the elements with the string returned from the server without refreshing the page. It's all automagic.

<html>
  <head>
    <title>Ajax Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">
      $(document).ready(
         function()
         {
           setInterval(
              function()
              {
                 $('.dynamic').each(
                    function()
                    {
                       $(this).load('ajax.php?id='+this.id);
                    }
                 );
              }, 1000);
         }
      );
    </script>
  </head>
  <body>
    <p>Ajax Example</p>
    <p class="dynamic" id="1">?</p>
    <p class="dynamic" id="2">?</p>
    <p class="dynamic" id="3">?</p>
    <p class="dynamic" id="4">?</p>
    <p class="dynamic" id="5">?</p>
  </body>
</html>

ajax.php

All this does is returns a string that contains a querystring value and a randomly generated number in a complete string.

<?
$id = $_GET['id'];
echo "The value is ".rand(1,100)." for id ".$id;
?>
Save the two files and open the index.html in a web browser using a URL to your web server. You should see something like the following, updating with different random numbers every second without refreshing the page.
Ajax Example
The value is 48 for id 1
The value is 16 for id 2
The value is 97 for id 3
The value is 99 for id 4
The value is 74 for id 5

Related Posts