[Latest News][6]

B.Sc.CSIT
Blogs
Laravel
Learn
News
Rentonnepal
Technology
A Complete Online Magazine

AddThis

How to make dependent dropdown list using jquery Ajax?

Step 1: Create Tables and Dummy Data
In first step we require to create database and tables for dependent dropdown example. So first you require to create "test" database in your phpmyadmin. After created database successfully we require to create two new table "demo_state" and "demo_cities" using following bellow SQL Query.
Image result for php image

demo_state table:

CREATE TABLE `demo_state` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

demo_cities table:

CREATE TABLE `demo_cities` (
  `id` int(11) NOT NULL,
  `state_id` int(12) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, in your database, you will have two tables "demo_state" and "demo_cities". Now we require to add some dummy data in both table like as bellow image.


Step 2: Create index.php file
In this step we will create index.php file, in this file we write code for state drop-down and city drop-down. In this file layout will display so put bellow code on index.php file.

index.php

<!DOCTYPE html>
<html>
<head>
    <title>PHP - How to make dependent dropdown list using jquery Ajax?</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
</head>
<body>
<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select State and get bellow Related City</div>
      <div class="panel-body">
            <div class="form-group">
                <label for="title">Select State:</label>
                <select name="state" class="form-control">
                    <option value="">--- Select State ---</option>
                    <?php
                        require('db_config.php');
                        $sql = "SELECT * FROM demo_state"; 
                        $result = $mysqli->query($sql);
                        while($row = $result->fetch_assoc()){
                            echo "<option value='".$row['id']."'>".$row['name']."</option>";
                        }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <label for="title">Select City:</label>
                <select name="city" class="form-control" style="width:350px">
                </select>
            </div>
      </div>
    </div>
</div>
<script>
$( "select[name='state']" ).change(function () {
    var stateID = $(this).val();
    if(stateID) {
        $.ajax({
            url: "ajaxpro.php",
            dataType: 'Json',
            data: {'id':stateID},
            success: function(data) {
                $('select[name="city"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
                });
            }
        });
    }else{
        $('select[name="city"]').empty();
    }
});
</script>
</body>

</html>

Step 3: Add DB Configuration File
Now we require to create db configuration file for database, that way you can set username, password, database and host. So let's create db_config.php file and put bellow code:

db_config.php

<?php
define (DB_USER, "root");
define (DB_PASSWORD, "root");
define (DB_DATABASE, "test");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

Step 4: Add Ajax File
In last step, we need to create ajax pro file, in this file we write code for dynamic ajax city drop-down json data. So let's create ajaxpro.php file and put bellow code:

ajaxpro.php

<?php
   require('db_config.php');
   $sql = "SELECT * FROM demo_cities
         WHERE state_id LIKE '%".$_GET['id']."%'"; 
   $result = $mysqli->query($sql);
   $json = [];
   while($row = $result->fetch_assoc()){
        $json[$row['id']] = $row['name'];
   }
   echo json_encode($json);
?>

Ok, now we are ready to run our example. So let's run bellow command on your root directory for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000

Good Luck !!

No comments:

Post a Comment

Start typing and press Enter to search