etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

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




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.