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 passing data from the server.

It is best and effective way to return data when you want to return multiple values as a response from AJAX.

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. AJAX
  5. jQuery
  6. Conclusion

 


 

1. Table structure

I am using users table in the tutorial 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 a new PHP file (config.php).

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" >
      <tr>
       <th width="5%">S.no</th>
       <th width="20%">Username</th>
       <th width="20%">Name</th>
       <th width="30%">Email</th>
      </tr>
   </table>
</div>

 

4. AJAX

Create a new getData.php file for sending AJAX request.

Initialize the array with the user details (id, username, name, and email) and before return converting 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 sending AJAX request.

Loop through all response values and append 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: 'getData.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").append(tr_str);
            }

        }
    });
});

 

6. Conclusion

In this tutorial, I showed how you can return 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.

Related Post

Spread the love

6 Comments

  1. Shuyaib said:

    Thank you. It’s the most simple explanation of sending multiple objects from php.

    May 18, 2017
    Reply
  2. MAYUR said:

    HI I WANT CREATE FUNCTION AND CALL THIS FUNCTION UING AJAX

    LIKE

    FUNCTION SELECT()
    {
    $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);
    }

    July 24, 2017
    Reply
    • Yogesh Singh said:

      You can do this way –

      jQuery –

      $.ajax({
        url: 'ajaxFile.php',
        type: 'post',
        data: {request: 1},
        success: function(data){
      
        }
      });
      

      PHP file (ajaxFile.php) –

      $request = $_POST['request'];
      if($request == 1){
         myfun1();
      }
      if($request == 2){
         myfun2();
      }
      function myfun1(){
       // Code
      }
      function myfun2(){
       // Code
      }
      
      July 24, 2017
      Reply
  3. Sanni said:

    Hey, so lets say the users have their profile saved n a database
    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,
    `updatedOn` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    how would I post this when they login fetching their profile using their username(unique) and email(unique) as sessions to display on homepage

    September 16, 2017
    Reply
    • Yogesh Singh said:

      Hi Sanni,
      You can check the $_SESSION variable on the AJAX file. If the session is set means the user is logged in then fetch its records otherwise return an empty array.

      September 16, 2017
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *