- Dynamically populating Selectboxes from Database
- $(document).ready(function() {
- $('#Region').change(function() {
- // remove all options in Area select
- $('#Area').html('');
- // find the new Region selected
- var selected_region = $('#Region').val();
- // get new options from server and put them in your Area select
- $('#Area').get('Ajax/getArea.php?Region=' + selected_region);
- });
- });
- <?php
- // get province id passed in via `post` or `get`
- $region = $_REQUEST['Region'];
- // get the districts in that province
- $query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
- // link to your database
- $link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
- // execute your query
- $result = mysqli_query($link, $query);
- // parse the options
- while($row = mysqli_fetch_assoc($result)) {
- $options = "<option value="".$row['AREA']."">".$row['AREA']."</option>n ";
- }
- // send options
- echo $options;
- ?>
- 1) the PHP code
- 2) The jQuery
- 3) The select box container
- :: Your PHP file (call it getArea.php)
- $selectbox = '<select name="region" onchange="jQuery.selectRegion(this.value)">';
- $region = $_REQUEST['Region']; /* Make sure you escape this */
- $query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
- $link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
- $result = mysqli_query($link, $query);
- $options = '';
- while($row = mysqli_fetch_assoc($result)) {
- $options .= '<option value="' . $row['AREA'] . '">' . $row['AREA'] . '</option>';
- }
- echo $selectbox;
- echo $options;
- echo '</select>';
- exit;
- :: Your jquery
- jQuery.selectRegion = function selectRegion(regionId)
- {
- $.get('ajax/getArea.php?region='+regionId,function(data){
- $('#select_container').html(data);
- });
- }
- :: The select box container
- <div id="select_container">
- <select name="region" onchange="jQuery.selectRegion(this.value)">
- <option value="1">Option 1</option>
- <option value="2">Option 2</option>
- </select>
- </div>