jQuery loop over JSON result after AJAX Success
In this article, you will learn how to loop over the JSON result or how to dynamically load subcategories of the selected category. For this, we have using AJAX to dynamically fetch data and then convert the Ajax response in JSON format. After that, we are using jQuery to iterate over the JSON response and print the subcategory selection drop down box of the selected category without refreshing the page.

Suppose, we have category and subcategory records in database as given below. You can use the records of category or subcategory if you already have otherwise you can create it manually or copy and paste the following queries in your database.
CREATE TABLE IF NOT EXISTS `category` (
`catid` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(100) NOT NULL,
`is_enabled` int(11) NOT NULL,
PRIMARY KEY (`catid`)
)
CREATE TABLE IF NOT EXISTS `subcategory` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cat_id` int(11) NOT NULL,
`subcategory_name` varchar(100) NOT NULL,
`is_enabled` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO `category` (`catid`, `category_name`, `is_enabled`) VALUES
(1, 'Accounting', 1),
(2, 'Technology', 1),
(3, 'Position', 1);
INSERT INTO `subcategory` (`id`, `cat_id`, `subcategory_name`, `is_enabled`) VALUES
(1, 1, 'Governement', 1),
(2, 1, 'Fund', 1),
(3, 1, 'Management', 1),
(4, 1, 'Social', 1),
(5, 1, 'Community', 1),
(6, 2, 'Nano', 1),
(7, 2, 'Agriculture', 1),
(8, 2, 'Radio', 1),
(9, 2, 'Information', 1),
(10, 3, 'Junior', 1),
(11, 3, 'senior', 1),
(12, 3, 'Team lead', 1),
(13, 3, 'Manager', 1);
1. db.php
Here, we have written the database connection code and defined a function that returns all enabled data from category table. Make sure to replace the 'hostname', 'username', 'password' and 'dbname' with your database credentials and name.
<?php
class Db {
private $hostname = 'hostname';
private $username = 'username';
private $password = 'password';
private $database = 'dbname';
private $conn = NULL;
public function __construct() {
$this->conn = mysqli_connect($this->hostname, $this->username, $this->password, $this->database);
if(!$this->conn) {
echo 'Database not connected';
}
}
public function getCategory(){
$query = "SELECT * FROM category WHERE is_enabled = '1'";
$result = mysqli_query($this->conn, $query);
return $result;
}
}
?>
2. getSubCategory.php
Again, we have created a PHP file to get subcategory records of the selected category. In this, we have stored the MySQL results into JSON representation using json_encode() method.
<?php
$catid = $_POST['catid'];
$json = array();
// MySQL database connection code
$connection = mysqli_connect("hostname","username","password","dbname") or die("Error " . mysqli_error($connection));
//fetch subcategories data
$sql = "SELECT * FROM subcategory WHERE cat_id = '$catid' ";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
//create an array
$json = array();
$i = 0;
while($row = mysqli_fetch_object($result))
{
$json[] = array('id' => $row->id, 'name' => $row->subcategory_name);
}
$data = json_encode($json);
echo $data;
?>
3. index.php
This is the main file, that we will call on the browser. In this file, we have written the Ajax code to dynamically fetch subcategory records of the selected category. On change category, the Ajax function calls the 'getSubCategory.php' file and creates the subcategory selection options.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getSubCategory(catid){
$.ajax({
url: 'getSubCategory.php',
data: 'catid='+catid,
type: 'POST',
success: function (data) {
var subcat = '<label>Sub Category</label>';
subcat += '<select name="subcatid" class="form-control">';
subcat += '<option value="0">Please Select Subcategory</option>';
data = $.parseJSON(data);
$.each(data, function(i, item) {
subcat += '<option value="'+item.id+'">'+item.name+'</option>';
});
subcat += '</select>';
$('div[id="subcat"]').html(subcat);
}
});
return false;
}
</script>
</head>
<body>
<div style="margin: 0 auto; width: 40%;">
<h2>Select category and their sub category</h2>
<?php
include 'db.php';
$model = new Db();
$category = $model->getCategory();
?>
<div class="form-group">
<label>Category </label>
<select name="category" onchange="getSubCategory(this.value)" class="form-control">
<option value="0">Please Select Category</option>
<?php
while($row = mysqli_fetch_array($category)) {
$catid = $row['catid'];
$cat_name = $row['category_name'];
echo '<option value="'.$catid.'">'.$cat_name.'</option>';
}
?>
</select>
</div>
<div class="form-group">
<div id="subcat"></div>
</div>
</div>
</body>
</html>
Related Articles
JavaScript display PDF in the browser using Ajax callHow to Retrieve Emails from Gmail using PHP IMAP
How to store Emoji character in MySQL using PHP
How to display PDF file in PHP from database
Dynamically Add/Delete HTML Table Rows Using Javascript
Submit a form data without page refresh using PHP, Ajax and Javascript
PHP Server Side Form Validation
How to add google reCAPTCHA v2 in registration form using PHP
Complete HTML Form Validation in PHP
CSS Simple Menu Navigation Bar
PHP MYSQL Advanced Search Feature