Return JSON response from AJAX using jQuery and PHP

JSON stands for JavaScript Object Notation, it is a data-interchange format which is also been used to pass data from the server.

It is the best and effective way when need to return multiple values as a response from the PHP script to the jQuery.

You couldn’t directly return an array from AJAX, it must have converted in the valid format.

In this case, you can either use 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.

On the basis of response show data in tabular format.

Return JSON response from AJAX using jQuery and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

1. Table structure

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. Configuration

Create  config.php for database configuration.

Completed Code

<?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. HTML

Create a <table id='userTable'> for displaying user list using AJAX response.

Completed Code

<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. PHP

Create ajaxfile.php file for handling AJAX request.

Initialize the $return_arr Array with the user details (id, username, name, and email), and before return convert it to JSON format using the json_encode() function.

Completed Code

<?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

On document ready state send an AJAX GET request to 'ajaxfile.php'.

Loop through all response values and append a new row to <table id='userTable'> on AJAX successfully callback.

Note – For handling JSON response you have to set dataType: 'JSON' while sending AJAX request.

Completed Code

$(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

In this tutorial, I showed how you can return the JSON response and handle it in jQuery AJAX.

You can convert the PHP array in JSON format with json_encode() function and return as a response. Set dataType: 'JSON' when send AJAX request.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.