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 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 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  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 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 state send an AJAX GET request.

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.

45 thoughts on “Return JSON response from AJAX using jQuery and PHP”

  1. 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);
    }

    Reply
    • 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
      }
      
      Reply
  2. 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

    Reply
  3. Hi nicely explained very easily, but i have a question is once button is clicked its ok.
    but if we click again button it show the same data again.
    i want to stop that only allowed once can u pls help me out

    Reply
    • Hi Savan,
      You can do this by creating a Boolean variable to store the status if the button is clicked or not. On button clicked fetch records and assign true to the variable. Only fetch record if a variable has false value.

      Reply
  4. hy i want to ask about “response”. In my case my .php that work for parsing a array to json format work properly but in my main .php, its just show undefine in every response[i] and length of response become 631. i dont know what is a cause . can you please help me to identified the problem?

    Reply
    • Hi Joe,
      You can do it like this –

      $stmt = $conn->prepare("Select * from users ORDER BY NAME");
      $stmt->execute();
      $result = $stmt -> get_result();
      while ($row = $result->fetch_assoc()){
          $id = $row['id'];
          $username = $row['username'];
          $name = $row['name'];
          $email = $row['email'];
      
          $return_arr[] = array("id" => $id,
              "username" => $username,
              "name" => $name,
              "email" => $email
          );
      }
      echo json_encode($return_arr);
      
      Reply
  5. Hi Yogesh,

    Here it is.

    $(document).ready(function(){
    /*alert(‘test’);*/
    $.ajax({
    url: ‘ajaxfile.php’,
    type: ‘get’,
    dataType: ‘JSON’,
    success: function(response){

    /*alert(response);*/

    var len = response.length;

    /*console.log(response);*/

    for(var i=0; i<3; i++){
    var id = response[i].id;
    var username = response[i].username;
    var name = response[i].name;
    var email = response[i].email;

    console.log(response);

    console.log(response[i].username);

    var tr_str = "” +
    “” + (i+1) + “” +
    “” + username + “” +
    “” + name + “” +
    “” + email + “” +
    “”;

    $(“#userTable tbody”).append(tr_str);
    }

    }
    });
    });

    Reply
  6. Hi Yogesh Singh, thank for this mini tutorial. How to know if the json data is captured by the ajax script? Apply your example to a code I’m working on and it doesn’t give me any results, the php file generated by the json is found in another directory

    Reply
      • Hi Yogesh, thanks for your answer, I look into every detail and nothing, in fact, I used your tutorial on my website and nothing, I got zero results, the only difference is the html code, in my case the html code is inside a php variable echoed in an index file, that’s the only difference. I don’t know what else I can do, I’m stuck in this stage for more than three days and nothing, would you give me a hand in this matter? I would really appreciate it

  7. hey great work!
    i am newbie.
    i need help!
    look i have 2 pages,
    1st page is waiting for response of 2nd page. but i need, when i submit form on 2nd page on isset($_POST[‘submit’]){send response to 1st page }. util then 1st page should wait for the response.
    give me all possible ways to communicate between two pages

    Reply
  8. Is there any body i need little help plz. I’m trying to access id from ajax response that is coming from database but when when i alert it or console it i only get single bracket ( { ).
    $.ajax({
    type : ‘post’,
    url : ‘main_controller/verify_email_for_password_reset’,
    data : {
    verify : verify
    },
    success : function(data)
    {
    var html = ‘ Change’;
    $(‘#test’).html(html);
    }
    });
    });

    $(‘#test’).on(‘click’,’#change_password’,function(){
    var id = $(this).data(‘id’);
    alert(id);

    Reply
  9. hi, please help me.
    i have try your example but i don’t see the value of response…
    html:

    ptf
    tipologia_ptf
    tipo_ptf
    venditore

    $(document).ready(function(){
    $.ajax({
    url: ‘trend_contratti_TOT.php’,
    type: ‘get’,
    dataType: ‘JSON’,
    success: function(response){
    var len = response.length;
    for(var i=0; i<len; i++){
    var ptf = response[i].ptf;
    var tipologia_ptf = response[i].tipologia_ptf;
    var tipo_ptf = response[i].tipo_ptf;
    var venditore = response[i].venditore;

    var tr_str = "” +
    “” + ptf + “” +
    “” + tipologia_ptf + “” +
    “” + tipo_ptf + “” +
    “” + venditore + “” +
    “”;

    $(“#userTable tbody”).append(tr_str);
    }

    }
    });
    });

    PHP:

    $ptf,
    “tipologia_ptf” => $tipologia_ptf,
    “tipo_ptf” => $tipo_ptf,
    “venditore” => $venditore);
    }

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

    $conn->close();
    ?>

    Reply
  10. Hello Sir,
    Sir i have a class and created a function for example:
    public static function getdetails(){
    //when this function called using ajax we do db query and return result this is working fine.
    echo json_encode($results);
    }

    Now what should i do if i need this function again inside this class for some other function like :

    public static function activateuser(){
    $result = self::getdetails(); // here this shows NULL as get details function already displayed records or something…
    }

    So, can you please help me how to do this as i could not want to use same function again and again for same results.

    Thanks
    Ashish

    Reply
  11. Thank you for this tutorial! In my case I need to send JSON data to the ajax file, then it uses that JSON for tasks and returns JSON back again to the first file. How would I do that?
    Thanks!

    Reply
  12. Hi Sir, Is it possible to implement your code without looping?

    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;

    And make it like this?

    success: function(response){
    var id = response.id;
    var username = response.username;
    var name = response.name;
    var email = response.email;

    Reply
  13. Yogesh ,

    Can you perhaps show me what I’m doing wrong here. I am very new to this. I am trying to do slide down child row in a datatable. I know I am close.

    function format ( object ) {
    let data=object;
    let x = ”;
    let txt=”;
    console.log(object);
    //data=object;

    try {
    if (x != undefined) {
    // Executes for declared variables that are not undefined nor null
    console.log( ‘X is okay ‘ + x)
    } // (Nothing happens)
    } catch (x) {
    console.log(‘Catch ‘ + x) // ReferenceError: x is not defined
    }
    //Json.parse(data);
    for (x in data) {
    txt += data[x].Tillid + ‘ Line No:’ + data[x].LineNo + ‘ ‘ +data[x].Productcode + ‘ ‘ + data[x].ProductDescription+’ ‘ + parseFloat(data[x].LineSalePriceIncDisc).toFixed(2) +”\n”;

    return ”+
    ”+
    ”+
    ‘Till Name:’+
    ”+ data[x].Tillid + ”+
    ‘Product Description:’+
    ”+”+”+
    ”+
    ”+
    ‘Customer Name:’+
    ”+ console.log(data[x].ProductDescription) +”+
    ”+
    ”+
    ‘Extra info:’+
    ‘And any further details here (images etc)…’+
    ”+
    ”;
    }
    }

    {Tillid: “MAINTILL”, LineNo: “1”, Productcode: “15479”, ProductDescription: “Cadent 1 Blk Lagre”, SingleSalePrice: “380.0000”, …}
    {Tillid: “MAINTILL”, LineNo: “2”, Productcode: “11571”, ProductDescription: “Helm 58-62 Mission EVO Silver”, SingleSalePrice: “19.9900”, …}

    Reply
  14. Sorry meant to say I am getting undefined in the tillname area of the slider i.e. txt is showing undefined. The slider is working okay it’s just what is being returned. The console log shows the data.

    function format ( object ) {
    const q=object;
    let x = ”;
    let txt=”;
    console.log(‘In format ‘ +object);
    //data=object;
    console.log(q[0][“Tillid”]);
    try {
    if (x != undefined) {
    console.log( ‘X is okay ‘ + x)
    for (x in data) {
    txt+= q[x].Tillid + ‘ ‘ + q[x].ProductDescription +’ ‘ + “\n”;
    }
    }
    } catch (x) {
    console.log(‘Catch ‘ + x) // ReferenceError: x is not defined
    }
    return ”+
    ”+
    ”+
    ‘Till Name:’+

    ”+ txt +”+
    ‘Customers Invoices:’+
    ”+”+”+
    ”+
    ”+
    ‘Customer Name:’+
    ”+ ‘view‘ +”+
    ”+
    ”+
    ‘Extra info:’+
    ‘And any further details here (images etc)…’+
    ”+
    ”;

    }

    Reply
  15. So i completely copied the code to test it, but the Table ist displayed in my case, but if i go to the ajaxfile.php i can see the data but it isnt displayed on the html site… whats the problem for that ?
    Im a beginner sorry

    Reply

Leave a Comment