Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 1.95 KB  |  hits: 4  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Dynamically populating Selectboxes from Database
  2. $(document).ready(function() {  
  3.    $('#Region').change(function() {
  4.   // remove all options in Area select
  5.  $('#Area').html('');
  6.   // find the new Region selected
  7.   var selected_region = $('#Region').val();
  8.   // get new options from server and put them in your Area select
  9.   $('#Area').get('Ajax/getArea.php?Region=' + selected_region);
  10.  
  11. });
  12. });
  13.        
  14. <?php
  15.  
  16. // get province id passed in via `post` or `get`
  17. $region = $_REQUEST['Region'];
  18.  
  19. // get the districts in that province
  20. $query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
  21.  
  22. // link to your database
  23. $link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
  24.  
  25. // execute your query
  26. $result = mysqli_query($link, $query);
  27.  
  28. // parse the options
  29. while($row = mysqli_fetch_assoc($result)) {
  30.  $options = "<option value="".$row['AREA']."">".$row['AREA']."</option>n  ";
  31. }
  32.  
  33.  
  34. // send options
  35. echo $options;
  36.  
  37. ?>
  38.        
  39. 1) the PHP code
  40. 2) The jQuery
  41. 3) The select box container
  42.        
  43. :: Your PHP file (call it getArea.php)
  44. $selectbox = '<select name="region" onchange="jQuery.selectRegion(this.value)">';
  45.  
  46. $region = $_REQUEST['Region'];      /* Make sure you escape this */
  47.  
  48. $query = "SELECT DISTINCT AREA FROM Sales_Execs WHERE Region ='$region'";
  49.  
  50. $link = mysqli_connect("localhost", "root", "", "Quality_Monitoring");
  51.  
  52. $result = mysqli_query($link, $query);
  53. $options = '';
  54. while($row = mysqli_fetch_assoc($result)) {
  55.     $options .= '<option value="' . $row['AREA'] . '">' . $row['AREA'] . '</option>';
  56. }
  57.  
  58. echo $selectbox;
  59. echo $options;
  60. echo '</select>';
  61.     exit;
  62.        
  63. :: Your jquery
  64.  
  65. jQuery.selectRegion = function selectRegion(regionId)
  66. {
  67. $.get('ajax/getArea.php?region='+regionId,function(data){
  68.     $('#select_container').html(data);
  69. });
  70. }
  71.        
  72. :: The select box container
  73. <div id="select_container">
  74. <select name="region" onchange="jQuery.selectRegion(this.value)">
  75.     <option value="1">Option 1</option>
  76.     <option value="2">Option 2</option>
  77. </select>
  78. </div>