Filling another drop-down list from the database based on the drop-down list

I create a website to study coding and try to create a tool in which the user presses a select / drop-down button containing some category names pulled from the cat database , and then another choice appears of the subcategory names pulled from the subcat database . It is almost the same as Yelp (go to categories) as Yelp (go to categories) .

I also made a diagram:

enter image description here

I already have a drop-down list of categories that is pulled from the cat database :

<p><b>Category:</b><br />
 <?php
  $query="SELECT id,cat FROM cat";
  $result = mysql_query ($query);
  echo"<select name='cselect3' class='e1'><option value='0'>Please Select A       Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
  echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']."    </option>";

  }

echo"</select>";
?>

And I have a subcat that pulls out a subcat database:

<p><b>Subcat1:</b><br />
<?php
  $query="SELECT id,subcat FROM subcat";
  $result = mysql_query ($query);
  echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
      echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";

  }

 echo"</select>";
?>

, ? !

+5
4

javascript php, javascript-. jquery AJAX.

, .. ie - catid, ...

<?php
  $db = new mysqli('localhost','user','password','dbname');//set your database handler
  $query = "SELECT id,cat FROM cat";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['id'], "val" => $row['cat']);
  }

  $query = "SELECT id, catid, subcat FROM subcat";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $subcats[$row['catid']][] = array("id" => $row['id'], "val" => $row['subcat']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcats);


?>

<!docytpe html>
<html>

  <head>
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcats = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("categoriesSelect");
        select.onchange = updateSubCats;
        for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);          
        }
      }
      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("subcatsSelect");
        subcatSelect.options.length = 0; //delete all options if any present
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
        }
      }
    </script>

  </head>

  <body onload='loadCategories()'>
    <select id='categoriesSelect'>
    </select>

    <select id='subcatsSelect'>
    </select>
  </body>
</html>
+18

, , , , ajax. , , , , ( jquery), .

// warning sub optimal jquery code 
$(function(){

   // listen to events on the category dropdown
   $('#cat').change(function(){

       // don't do anything if use selects "Select Cat"
       if($(this).val() !== "Select Cat") {

           // subcat.php would return the list of option elements 
           // based on the category provided, if you have spaces in 
           // your values you will need to escape the values
           $.get('subcat.php?cat='+ $(this).val(), function(result){
               $('#subcat').html(result);
           });

       }

   });

});
+3

AJAX, , php, AJAX. AJAX (): someContainingDivOrSomething.innerHtml = responseBody;.

, PHP ( ). , . .

0

make this html structure on the landing page

<p><b>Category:</b><br />
 <?php
  $query="SELECT id,cat FROM cat";
  $result = mysql_query ($query);
  echo"<select name='cselect3' onChange='loadSubCats(this.value)' class='e1'><option value='0'>Please Select A       Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
  echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']."    </option>";

  }

echo"</select>";
?>

<div id='sub_categories'></div>

make js function assigned to category dropdown

function loadSubCats(value)
{
  $.post('load_sub_cats.php',{catid : value},function{data}
                                             {
                                              $('#sub_categories').html(data);

                                             });

}

now in your load_sub_cats.php

<p><b>Subcat1:</b><br />
<?php
  $catid = $_POST['cat_id']
  $query="SELECT id,subcat FROM subcat where catid = $catid";
  $result = mysql_query ($query);
  echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
      echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";

  }

 echo"</select>";
?>

You will need to include jquery in this code work.

0
source

All Articles