How to load dropdown when change another dropdown from MySQL using jQuery Ajax in PHP.


This example shows, how to load second dropdown when first dropdown onchange from MySQL database using jQuery Ajax in PHP.

Output

Dropdown onchange load another Dropdown from PHP MySQL using jQuery Ajax.

In this example we used three PHP files,

  • config.php
  • load_products.php
  • index.php

Step 1: Create db_sample MySQL database.

CREATE DATABASE db_sample;

Step 2: MySQL query for create category Table

CREATE TABLE  category(
  `cid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cname` varchar(45) NOT NULL DEFAULT '',
  PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Step 3: MySQL query for create products Table

CREATE TABLE  products(
  `pid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pname` varchar(45) NOT NULL DEFAULT '',
  `price` double(10,2) NOT NULL DEFAULT '0.00',
  `cid` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

config.php

<?php 
  //MySQL Db Connection
  $host_name="localhost";
  $user_name="root";
  $password="";
  $db_name="db_sample";
  $con=mysqli_connect($host_name, $user_name, $password, $db_name);
?>

load_products.php

<?php 
  include "config.php";
  $sql="select pid,pname from products where cid='{$_POST["id"]}'";
  $res=$con->query($sql);
  echo "<option value=''>Select Product</option>";
  if($res->num_rows>0){
    while($row=$res->fetch_assoc()){
      echo "<option value='{$row["pid"]}'>{$row["pname"]}</option>";
    }
  }
?>

index.php

<?php include "config.php";?>
<html>
  <body>
    <p>
      <label>Categories : </label>
      <select id='category'>
        <option value=''>Select Category</option>
        <?php 
          $sql="select * from category";
          $res=$con->query($sql);
          if($res->num_rows>0){
            while($row=$res->fetch_assoc()){
              echo "<option value='{$row["cid"]}'>{$row["cname"]}</option>";
            }
          }
        ?>
      </select>
    </p>
    <p>
      <label>Products : </label>
      <select id='product'>
        <option value=''>Select Product</option>
      </select>
    </p>
    
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script>
      $(document).ready(function(){
        $("#category").change(function(){
          var cid=$(this).val();
          $.ajax({
            url:'load_products.php',
            type:'post',
            data:{id:cid},
            success:function(res){
              $("#product").html(res);
            }
          });
        });
      });
    </script>
  </body>
</html>