×


jQuery loop over JSON result after AJAX Success

In this post, you will learn how to loop over the JSON result or how to dynamically load subcategories of the selected category.









JSON (JavaScript Object Notation) is a lightweight, open standard file format. It is an array data type consisting of attribute–value pairs. It is easy to read and write for humans. It is used primarily to transmit data between a web application and a server. JSON is popular among developers for data serialization. It is so popular that every modern programming language has methods to generate and parse JSON formatted data.

Ajax provides the ability to dynamically change portions of a web page without reloading the entire web page. Some portions of a web page are static, like the header, footer, and menus, and need to be reloaded when the user interacts with the page. The reloading of the page takes extra user time. You have experienced that when you click on some request, that page may hang because a lot of information is trying to load at once.





Here, we have used 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.

jQuery loop over JSON result after AJAX Success

Suppose we have category and subcategory records in the database as given below. You can use the records of a category or a subcategory if you already have them; otherwise, you can create them manually or copy and paste the following queries into 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 the 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 for the selected category. In this, we have stored the MySQL results into JSON representation using the 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 in the browser. In this file, we have written the Ajax code to dynamically fetch subcategory records of the selected category. On changing the 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

Generate random numbers in JavaScript
How to reverse a number in Javascript
Remove duplicates from array Javascript
How to reverse string in JavaScript
JavaScript speech recognition example
jQuery Ajax serialize form data example
Ajax live data search using jQuery PHP MySQL
Bootstrap modal popup example on page load
Image popup on page load using HTML and jQuery
jquery sticky header on scroll
JavaScript display PDF in the browser using Ajax call
PHP script to read email inbox
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








Read more articles


General Knowledge



Learn Popular Language