Matt Molsberry Matt Molsberry - 5 months ago 13
jQuery Question

populating a 2nd select box based off the 1st one using ajax and PHP

I'm going a little nuts here. I know this has been answered a few times before but I can't seem to get it. I must be missing something very obvious.

I need the options of the second select input to be dynamically populated from a DB based on selection of the 1st select input. I have tested the getShowByBand.php code and it produces the intended results. My guess is the problem lies in the javascript file. Please take a look at my code and see if you can help.

testForm.php

<form role="form">
<div class="well" id="generalIDRows">
<div class="row">
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="band">Choose Band:</label>
<select id="band" name="band" class="form-control">
<option value="">Band Name</option>
<?php
$sql = "SELECT bandID,bandName FROM Band";
$bandq = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($bandq))
{
$band_ID=$row["bandID"];
$band=$row["bandName"];
echo '<option value="' . $band_ID . '">' . $band .'</option>';
}
?>
</select>
<script src="js/getShowByBand.js" type="text/javascript"></script>
</div>
</div>
<div class="col-md-6 padding-top-10">
<div class="form-group">
<label for="show">Choose Show:</label>
<select id="show" name="show" class="form-control">
<option value="">--Select Show--</option>
</select>
</div>
</div>
</div>
</div>
</form>


getShowByBand.js

$(document).ready(function()
{
$(".band").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "womhScripts/getShowByBand.php",
data: dataString,
cache: false,
success: function(html)
{
$(".show").html(html);
}
});
});
});


getShowByBand.php

<?php
$link=mysqli_connect("localhost","womhproduction","Derkadeepd0ng","womh");
if (mysqli_connect_errno())
echo "failed to connect" . mysqli_connect_error();
if($_POST)
{
$id=$_POST['id'];
$showSQL = mysqli_query($link,"SELECT showID FROM Act WHERE bandID =" . $id . ";");
$showResults = mysqli_num_rows($showSQL);
if($showResults > 0)
{
echo "<option selected disabled>--Select show--</option>";
while($showRow = mysqli_fetch_array($showSQL))
{
$showID= $showRow['showID'];
$showNameSQL = mysqli_query($link, "SELECT showName FROM Shows WHERE showID=". $showID . ";");
$showNameResults = mysqli_num_rows($showNameSQL);
if($showNameResults > 0)
{
while($showNameRow = mysqli_fetch_array($showNameSQL))
{
$showName = $showNameRow['showName'];
echo '<option value= "' . $showID . '">' . $showName . '</option>';
}
}
}
}
}
?>

Answer

Use $("#band").change... dot is used to select class.