Return JSON response from AJAX using jQuery and PHP

JSON or JavaScript Object Notation is a widely used transmitting format for passing data between a server and a web application. It is the most efficient way to return multiple values as a response from the PHP script to jQuery.

It is not possible to return an array directly from AJAX, and it must be converted into a valid format. You can either use the XML or JSON format.

In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.

Based on response show data in tabular format.

Return JSON response from AJAX using jQuery and PHP


Table of Content

  1. Create a Table
  2. Database connection
  3. Create HTML Layout
  4. AJAX – Returning JSON Response from PHP
  5. jQuery – Send AJAX Request and handle JSON Response
  6. Demo
  7. Conclusion

1. Create a Table

I am using users table in the example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Database connection

Create  config.php for database configuration.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

3. Create HTML Layout

Create an HTML table element with an id of "userTable" to display the user list using the AJAX response.

<div class="container">
   <table id="userTable" border="1" >
      <thead>
         <tr>
             <th width="5%">S.no</th>
             <th width="20%">Username</th>
             <th width="20%">Name</th>
             <th width="30%">Email</th>
         </tr>
      </thead>
      <tbody></tbody>
   </table>
</div>

4. AJAX – Returning JSON Response from PHP

Create ajaxfile.php to handle AJAX requests. Inside the file, create an array called $return_arr to store the response that will be sent back to the client.

Next, fetch all records from the users table and loop through them. For each user, add their details (id, username, name, and email) to the $return_arr array.

Finally, using json_encode() function convert $return_arr Array to JSON format before returning it to the client side.

<?php

include "config.php";

$return_arr = array();

$query = "SELECT * FROM users ORDER BY NAME";

$result = mysqli_query($con,$query);

while($row = mysqli_fetch_array($result)){
    $id = $row['id'];
    $username = $row['username'];
    $name = $row['name'];
    $email = $row['email'];

    $return_arr[] = array("id" => $id,
                    "username" => $username,
                    "name" => $name,
                    "email" => $email);
}

// Encoding array in JSON format
echo json_encode($return_arr);

5. jQuery – Send AJAX Request and handle JSON Response

An AJAX GET request is sent to ajaxfile.php once the document has reached the ready state. A new row is added to the table with the ID userTable after a successful callback, which loops through all response values.

In AJAX request set dataType to 'json' to handle the JSON response or you can use JSON.parse() to convert returned JSON string to an object.

$(document).ready(function(){
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(response){
            var len = response.length;
            for(var i=0; i<len; i++){
                var id = response[i].id;
                var username = response[i].username;
                var name = response[i].name;
                var email = response[i].email;

                var tr_str = "<tr>" +
                    "<td align='center'>" + (i+1) + "</td>" +
                    "<td align='center'>" + username + "</td>" +
                    "<td align='center'>" + name + "</td>" +
                    "<td align='center'>" + email + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

        }
    });
});

6. Demo

View Demo


7. Conclusion

The PHP array must be encoded into JSON using the json_encode() function before a response can be returned. To handle returned JSON response you can either set dataType to ‘json’ or use JSON.parse() function.

With practice and further exploration, you can use these concepts to build more advanced and interactive web applications.

Additionally, you may refer to a tutorial to learn how to send a JavaScript array with an AJAX request.

If you found this tutorial helpful then don't forget to share.