Return PHP Array as JSON Data in jQuery Ajax Request Tutorial

In this tutorial, we will tackle about How to Return PHP Array as JSON Data in Ajax Request. Here, I will show you a way on achieving this goal for your current or future project. I will also provide snippets for this tutorial and a sample source code that demonstrates the idea of this tutorial.

What is Array?

Array is a data structure that contains a collection of elements store at contiguous memory location. Each element of an Array is identified by at least one array index or key.

What is JSON?

JSON stands for JavaScript Object Notation.It is a lightweight format for storing and transporting. Also, it is often used when data is sent from the server to a certain web page. JSON is constructed with name and value pairs and each element or data are being separated using a comma and enclosed using curly brackets {}.

How to Return PHP Array as JSON Data in Ajax Request?

To Return of Echo PHP Array as JSON Data, we will be using the application/json content-type on the header and echoing or displaying the array using json_encode function of the PHP.

Here is an example snippet for return PHP Array as JSON Data.

  1. <?php
  2. // Set Header content type
  3. header("Content-type: application/json");
  4.  
  5. // Sample Array Data
  6. $arr = ["id":1, "data": "Sample Data Only."];
  7.  
  8. // Echo Array data as JSON
  9. echo json_encode($arr);
  10. ?>
  11.  

Sample Source Code

Now, I will be providing a simple application that demonstrates the topic for this tutorial. The simple application displays a list of data stored in a JSON File shown in a table element. Each table row has a View Details button which triggers the jQuery Ajax Requests that getting the complete details of data. The data will be returned as a JSON Data and will be shown on the Details Display Panel below the table.

JSON File

The below data is the sample JSON Data to be use in the sample application.

  1. [{
  2. "id":1,
  3. "name": "Mark Cooper",
  4. "address": "23 St. Here City, Anywhere, 2306",
  5. "contact": "09123456987"
  6. },{
  7. "id":2,
  8. "name": "John Smith",
  9. "address": "6 St. Here City, Anywhere, 2306",
  10. "contact": "09789456123"
  11. },{
  12. "id":3,
  13. "name": "Samantha Lou",
  14. "address": "14 St. Down There City, Over There, 1415",
  15. "contact": "09456987123"
  16. },{
  17. "id":4,
  18. "name": "Cristine Lee",
  19. "address": "15 St. Down There City, Over There, 1415",
  20. "contact": "09321987456"
  21. },{
  22. "id":5,
  23. "name": "Joshua Miller",
  24. "address": "1234 St. XXX City, XXXXXXX, 1014",
  25. "contact": "09456654123"
  26. }]

Interface

The following script is an HTML and PHP code for displaying the page elements or interface.

  1. <div class="container-fluid py-4 my-2">
  2. <h1 class="text-center fw-bold text-white">Returning PHP Array as JSON in jQuery Ajax</h1>
  3. <hr class="border-light">
  4. <div class="card rounded-0 shadow col-lg-6 col-md-10 col-sm-12 mx-auto">
  5. <div class="card-header">
  6. <div class="card-title">
  7. Sample Data
  8. </div>
  9. </div>
  10. <div class="card-body">
  11. <div class="container-fluid">
  12. <?php
  13. $data = json_decode(file_get_contents("data.json"));
  14. ?>
  15. <table class="table table-bordered table-hover table-striped">
  16. <col width="10%">
  17. <col width="60%">
  18. <col width="30%">
  19. <tr class="bg-primary text-light">
  20. <th class="text-center">ID</th>
  21. <th class="text-center">Name</th>
  22. <th class="text-center">Action</th>
  23. </tr>
  24. </thead>
  25. <?php foreach($data as $row): ?>
  26. <tr>
  27. <td class="text-center"><?= $row->id ?></td>
  28. <td><?= $row->name ?></td>
  29. <td class="text-center">
  30. <button class="btn btn-primary btn-sm rounded-0 view_details" type="button" data-id="<?= $row->id ?>">View Details</button>
  31. </td>
  32. </tr>
  33. <?php endforeach; ?>
  34. </tbody>
  35. </table>
  36. </div>
  37. </div>
  38. </div>
  39. <div class="mt-3" id="details">
  40. <div class="card rounded-0 shadow col-lg-4 col-md-8 col-sm-12 mx-auto">
  41. <div class="card-header rounded-0">
  42. <div class="card-title"><b>Details</b></div>
  43. </div>
  44. <div class="card body rounded-0">
  45. <div class="container-fluid">
  46. <dl class="row">
  47. <dt class="col-lg-4">ID:</dt>
  48. <dd class="col-lg-8" id="id"></dd>
  49. </dl>
  50. <dl class="row">
  51. <dt class="col-lg-4">Name:</dt>
  52. <dd class="col-lg-8" id="name"></dd>
  53. </dl>
  54. <dl class="row">
  55. <dt class="col-lg-4">Contact #:</dt>
  56. <dd class="col-lg-8" id="contact"></dd>
  57. </dl>
  58. <dl class="row">
  59. <dt class="col-lg-4">Address:</dt>
  60. <dd class="col-lg-8" id="address"></dd>
  61. </dl>
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. </div>

JS jQuery and Ajax Script

Here's the script for executing the Ajax Request when clicking the View Details of each table rows.

  1. $(document).ready(function(){
  2. $('.view_details').click(function(e){
  3. e.preventDefault();
  4. var id = $(this).attr('data-id')
  5. $.ajax({
  6. url:"get_data.php?id="+id,
  7. dataType:"json",
  8. error:err => {
  9. console.error(err)
  10. },
  11. success: function(response){
  12. $('#id').text(response.id)
  13. $('#name').text(response.name)
  14. $('#contact').text(response.contact)
  15. $('#address').text(response.address)
  16. }
  17. })
  18. })
  19. })

PHP Script

Here's the PHP Script that demonstrates how to return PHP Array as JSON Data in Ajax Request.

  1. <?php
  2. header("Content-type: application/json");
  3. $id = $_GET['id'];
  4. $data = json_decode(file_get_contents("data.json"));
  5. $data_array = [];
  6. foreach($data as $row){
  7. $data_array[$row->id] = $row;
  8. }
  9.  
  10. $resp = $data_array[$id];
  11. echo json_encode($resp);
  12. ?>

Snapshot

Here's the sample snapshot for the result or output of the sample application.

Returning PHP Array as JSON in Ajax Request

DEMO VIDEO

The full source code of this sample application is provided on this website. To download the source code zip file, click the download button below this article.

There you have it! I hope this tutorial will help you with what you are looking for and adds up to your knowledge for developing a web application using PHP and jQuery. Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
2 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.