AJAX and JSON

Introduction

Ajax (AJAX) stands for Asynchronous JavaScript And XML request. It is a set of techniques using on the client side to create asynchronous requests to the server. With Ajax, web applications can send and retrieve data from a server without interfering with the display and behaviour of the existing page. Ajax allows web apps to change content without the need to reload the entire page. The X in AJAX stands for XML ,which used to be the dominant hierarchical data format. However, today JSON has taken over in popularity so nowadays we should talk about AJAJ request but for historical reasons they are still called Ajax.

JSON

JSON stands for JavaScript Object Notation. It is an open standard data interchange format, that uses human-readable text strings consisting in key-value pairs to store and transmit data.

Here is a basic example of what might be a JSON string:

{
  "foreName": "John",
  "familyName": "Doe",
  "dateOfBirth": "1984-11-16"
}

The official internet media type for JSON is application/json and files use the extension .json

Even though these two items refer to. JavaScript in their names, both AJAX and JSON are language-independent. They were derived from JavaScript but may modern  programming languages include code to generate and/or parse JSON format data.

Performing an Ajax GET request

Let's consider the following example:

A web page makes an Ajax request to asychronously search a user list. The page will show the matching records without reloading the whole page from the server.

Server side

Here's the server side file users.php that outputs a JSON string returning the filtered list of users:

<?php

$dataArray = array(
  array(
    "forename" => "Anthony",
    "surname" => "Smith",
    "age" => 25,
    "nationality" => "British",
    "username" => "anthonys",
    "email" => "anthonys@sreb.com"
  ),
  array(
    "forename" => "Antonio",
    "surname" => "Ferrari",
    "age" => 37,
    "nationality" => "Italian",
    "username" => "aferrari",
    "email" => "aferrari@sreb.com"
  ),
  array(
    "forename" => "Antonio",
    "surname" => "Herrero",
    "age" => 22,
    "nationality" => "Spanish",
    "username" => "antoniohr",
    "email" => "antoniohr@sreb.com"
  ),
  array(
    "forename" => "Antoine",
    "surname" => "Forgeron",
    "age" => 53,
    "nationality" => "French",
    "username" => "antforgeron",
    "email" => "antforgeron@sreb.com"
  )
);

$searchData = array(
  "forename" => $_GET["forename"],
  "surname" => $_GET["surname"],
  "age" => $_GET["age"],
  "nationality" => $_GET["nationality"],
  "username" => $_GET["username"],
   "email" => $_GET["email"],  
);

$result = array_reduce($dataArray, 
  function($carry, $element) use ($searchData)
  {
    if ($element["forename"] == $searchData["forename"]
        || $element["surname"] == $searchData["surname"]
        || $element["age"] == $searchData["age"]
        || $element["nationality"] == $searchData["nationality"]
        || $element["username"] == $searchData["username"]
        || $element["email"] == $searchData["email"]
     )
     {
       array_push($carry, $element);
     }
     
     return $carry;
  },
  array());

echo(json_encode($result));

Front end

And here's the HTML file that will show the search form:

<!DOCTYPE html>
<html>
  <body>
    <h1>User Search Form</h1>
    <form id="userSearch"> 
      <label> First name:</label><br>
      <input type="text" name="forename"><br>
      <label> Family name:</label><br>
      <input type="text" name="surname"><br>
      <label> Age: </label><br><input type="text" name="age"><br>
      <label> Nationality:</label><br>
      <select name="nationality">
      	<option>British</option>
        <option>Italian</option>
        <option>Spanish</option>
        <option>French</option>
      </select><br>
      <label> Username:</label><br>
      <input type="text" name="username"><br>
      <label> Email:</label><br>
      <input type="text" name="email"><br>
      <input type="submit" value="Submit">
    </form>

    <h3>Results</h3>
    <table id="usersTable">
    	<tr><th>Name</th><th>Age</th><th>Nationality</th><th>Username</th><th>Email</th></tr>
    </table>
    
    <script>
    // JavaScript code to make the AJAX request
    </script>
  </body>
</html>

Ajax request

Lastly, let's use jQuery to do the asynchronous call to the server and populate the results table.

$(document).ready(function(){
  $("#userSearch").submit(function(event){
  event.preventDefault();
  $.ajax(
    {
      url: "users.php",
      data: $("#userSearch").serialize(),
      success: function(response){
        $.each(data, function(index, obj) {
          $("#usersTable").append("<tr><td>" + obj.forename + " " + obj.surname + "</td><td>" + obj.age + "</td><td>" + obj.nationality + "</td><td>" + obj.username + "</td><td>" + obj.email + "</td></tr>");
    	});
      }
    });
  });
});

Conclusion

With this simple example, I have tried to laid the basics of what it is to make AJAX requests and use JSON format as output data, using PHP, JavaScript and JQuery. This is, of course a very simple educational example. A real case would retreive the data from a DB and would have the complexities of dealing with security issues.