How to Load JSON Data Dynamically in PHP and jQuery

Learn how to populate dropdowns dynamically using JSON, PHP, and jQuery. Real-world example with departments and employees using AJAX and JSON data.

📚 Introduction

In many PHP web projects, you’ll often need to create dependent dropdowns or load dynamic data based on user selection — like choosing a department to view its employees.

In this guide, we'll walk through a complete example where:

  • PHP loads a dropdown from a JSON API
  • When the user selects an option, another PHP script fetches related data using AJAX
  • jQuery updates the page with no reload

This type of setup is commonly used in dashboards, admin panels, and business apps.

 

🧠 The Scenario

We are building a basic interface that:

  1. Loads department names into a <select> dropdown (from a PHP-generated JSON file)
  2. On selection, uses jQuery AJAX to fetch a list of employees in that department
  3. Displays the employee list dynamically below the dropdown

 

❌ The Problem (That You Might Face)

When building such functionality, developers often run into issues like:

  • Dropdown remains empty
  • AJAX call succeeds but returns no data
  • Warnings like foreach() argument must be of type array|object, null given
  • json_decode() returns null or fails silently

 

🔎 Common Causes of These Issues

Issue Likely Cause
foreach() on null json_decode() failed or file couldn’t be loaded
Empty AJAX response JSON file doesn't exist or is malformed
No error shown AJAX call failed silently, no .fail() handler
Incorrect output Echoing HTML or spaces before JSON in PHP

 

✅ Working Solution (3 Files)

📁 1. departmentsJSON.php

This file returns department names in JSON format. Think of it as a fake API or static service.

<?php
header('Content-Type: application/json');

$departments = [
  ["name" => "HR"],
  ["name" => "Engineering"],
  ["name" => "Marketing"]
];

echo json_encode($departments);

📁 2. getEmployeesJSON.php

This file receives the selected department via query parameter and returns employee names as JSON.

<?php
header('Content-Type: application/json');

$department = $_GET['department'] ?? '';
$employees = [];

$data = [
  'HR' => ['Alice', 'Bob'],
  'Engineering' => ['Charlie', 'David'],
  'Marketing' => ['Ella', 'Frank']
];

if (isset($data[$department])) {
  $employees = $data[$department];
}

echo json_encode($employees);

📄 3. index.php

This is the main frontend. It loads departments using PHP and handles user interaction via jQuery.

<?php
$json = file_get_contents('http://localhost/demo/departmentsJSON.php');
$obj = json_decode($json, false);
?>

<p>Select a department to view employees:</p>
<select id="deptSelect">
  <option value="">-- Choose Department --</option>
  <?php foreach ($obj as $dept): ?>
    <option value="<?= $dept->name ?>"><?= $dept->name ?></option>
  <?php endforeach; ?>
</select>

<div id="employeeList"></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
  $('#deptSelect').change(function () {
    var selectedDept = $(this).val();

    if (selectedDept !== '') {
      var url = "http://localhost/demo/getEmployeesJSON.php?department=" + encodeURIComponent(selectedDept);

      $.getJSON(url)
        .done(function (data) {
          var html = "<h3>Employees:</h3><ul>";
          $.each(data, function (i, employee) {
            html += "<li>" + employee + "</li>";
          });
          html += "</ul>";
          $('#employeeList').html(html);
        })
        .fail(function (jqxhr, status, error) {
          $('#employeeList').html("<p style='color:red;'>Error loading employees.</p>");
          console.error("AJAX Error:", status, error);
        });
    } else {
      $('#employeeList').html('');
    }
  });
});
</script>

 

🔧 Debugging Checklist

  • Make sure your JSON files are reachable and return clean data
  • Use browser Network tab to inspect AJAX response
  • Don’t echo extra HTML or spaces before json_encode()
  • Use .fail() handler in jQuery for debugging

 

📌 Conclusion

Chained JSON-based dropdowns are very useful for building interactive UIs in PHP. This example covers how to do it cleanly using:

  • JSON as data exchange format
  • PHP to serve both static and dynamic data
  • jQuery to power the frontend interaction

Once you understand the pattern, you can scale this technique to more advanced cases like:

  • Category → Subcategory
  • Country → State → City
  • Brand → Product → Details

 

📘 Bonus Tip

If you're working on larger applications, consider storing these JSON files separately (e.g., /api/) or generating them from a database instead of arrays.