user3449007 user3449007 - 1 year ago 34
PHP Question

Populate second select list based on first select list value

I'm trying to do a nested select list which is not working The values of the second select list dont get populated. Here is my code. I populate the first select and based on its value getter.php is called dynamically to populate the second select box (which is not working)

<div class="col-sm-3">
<label for="rg">Region</label>
<div class="col-sm-9">
<select id="region" name="region">
<option value="">Select Region</option>
<option value="AR">Ashanti</option>
<option value="BRONG+AHAFO">Brong Ahafo</option>
<option value="CENTRAL">Central</option>
<option value="EASTERN">Eastern</option>
<option value="GREATER+ACCRA">Greater Accra</option>
<option value="NORTHERN">Northern</option>
<option value="UPPER+EAST">Upper East</option>
<option value="UPPER+WEST">Upper West</option>
<option value="VOLTA">Volta</option>
<option value="WESTERN">Western</option>

<div class="col-sm-3"><label for="tw">Town</label></div>
<div class="col-sm-9">
<select id="town" name="town">
<option value="">Select Town</option>


<script type="text/javascript">
$(document).ready(function() {
$("#region").change(function() {
$("#town").load("getter.php?choice=" + $("#region").val());

Here is getter.php

include "../areashoppers/includes/cs_functions.php";
$sql = "SELECT distinct town FROM oic_areas_full WHERE region = '".$choice."' ORDER BY town ASC";
$st = $sc_conn->query($sql);
while ($r = $st->fetch()) {
echo "<option>" . $r['town'] . "</option>";

This is what shows in the error log

[02-Aug-2016 18:39:50 UTC] PHP Notice: Undefined variable: choice in /home/areashoppers/public_html/nylb/getter.php on line 3

[02-Aug-2016 18:39:50 UTC] PHP Fatal error: Call to a member function fetch() on boolean in /home/areashoppers/public_html/nylb/getter.php on line 5

$sc_conn is my DSN defined in cs_functions

Answer Source

Undefined variable: choice is most likely causing the second error as well, since the query will fail if $choice is not defined.

$choice = $_GET['choice'];

at the beginning of the PHP script should clear up the error.

Including a variable in the query string like getter.php?choice=something does not automatically create a $choice variable, but it does store the value in $_GET['choice'].

If you want to safely use the $choice variable in your query, don't worry about escaping it, just use a prepared statement. Assuming $sc_conn is a working PDO connection, that would be like this:

$sql = "SELECT distinct town FROM oic_areas_full WHERE region=? ORDER BY town ASC";
$st = $sc_conn->prepare($sql);