internally1
internally1

Reputation: 97

making cascading dropdown using jquery,php and mysql

am trying to make a cascading dropdown, i want when a user select region then city dropdown is populated accordingly..

JS:

$(document).ready(function() {
    $('#region').change(function() {
        var region = $(this).val();
        $.post('get_region.php', {
            region: region
        }, function(data) {
            $('#district_div').html(data);
        });
    });

PHP:

<?php
require_once('../db/connect.php');

$region=$_POST['region'];

$q=mysql_query("select name from city where region='$region'");

$row=mysql_fetch_array($q);
echo $row['name']; 
?>

HTML*strong text*

 <div class="controls">

                       <select class="bootstrap-select" name="region" id="region">
                                          <option value="">Choose</option>
                                      //from database
                                          <?php echo $region_result; ?>

           </select>
  </div>

                       <select class="bootstrap-select" name="district" id="district" >

                             <div id='district_div'></div>         

          </select>

Upvotes: 0

Views: 2654

Answers (3)

Ryan
Ryan

Reputation: 11

-for JS it should be like this-

$(document).ready(function() {
    $('#region').change(function() {
        var region = $(this).val();
        $.post('get_region.php', {
            region: region
        }, function(data) {
            $('#district').html(data); // I change this part
        });
    });


-for php-

<?php
require_once('../db/connect.php');

$region=$_POST['region'];

$q=mysql_query("select name from city where region='$region'");

while($row = mysql_fetch_array($q)){
   echo "<option>".$row['name']."</option>";
}

?>


-for the html

<div class="controls">
   <select class="bootstrap-select" name="region" id="region">
      <option value="">Choose</option>
      //from database
      <?php echo $region_result; ?>
    </select>

     <select class="bootstrap-select" name="district" id="district" >

     </select>     <!--you don't need to put a div in the select tag-->
</div>

Upvotes: 1

Hern&#227; Saldanha
Hern&#227; Saldanha

Reputation: 299

You are trying to write plain text inside a select box. Try to write in HTML format:

<option>name</option>

In your JS, replace the line:

$('#district_div').html(data);

With:

$('#district').html(data);

Delete the DIV with id "district_div". You cannot have a DIV inside a SELECT. In PHP, the last line is:

echo "<option>$row[name]</option>";

Upvotes: 0

Miguelo
Miguelo

Reputation: 1078

you mis some pieces

// will echo the name value of one row
    $row=mysql_fetch_array($q);
    echo $row['name']; 

try

$results = array();
while($row = mysql_fetch_array($q)){
$results[] = '<option>.'$row['name'].'</option>';
}
$optionString= implode(' ', $results);
echo $optionsString;

Upvotes: 0

Related Questions