GonHL GonHL - 7 months ago 29
PHP Question

Call PHP via AJAX

My user needs to pick an option from a first

<select>
and according to his selection, a second
<select>
should offer different options.

You may have seen this when picking a State after picking a Country in many many websites.

I know there are hundred other questions like this but I have tried lots of their answers without any success.

So, here is where I am standing right now:

<div class="col-md-2">
<span class="input-group-addon" id="basic-addon1" style="border:solid 1px #CCC; border-radius:4px;">Juzgado: </span>
<select class="form-control" id="juz" name="juz">
<option value="1">Juzgado 1</option>
<option value="2">Juzgado 2</option>
<option value="3">Juzgado 3</option>
</select>
</div>

<div class="col-md-2" id="nomDiv">
<span class="input-group-addon" id="basic-addon1" style="border:solid 1px #CCC; border-radius:4px;">Nominación: </span>
<select class="form-control" id="nom" name="id_juz_nom">

</select>
</div>


Then... my AJAX

<script type='text/javascript'>
$(document).ready(function(){
$('select[name=juz]').on('change', function() {

var juz = $(this).val()

$.ajax({
url: "tomarNominaciones.php",
type: "POST",
data: { juz.value },

success: function (response) {

document.getElementById('nom').innerHTML= response;

}
});
});
});

</script>


And finally this is my PHP:

<?php
$juz = $_POST['juz'];
include 'conectar.php';
mysql_select_db('juz_nom');
$query = "SELECT * FROM juz_nom WHERE juzgado=\"".$juz."\"";
$result = mysql_query($query);
?>

<span class="input-group-addon" id="basic-addon1" style="border:solid 1px #CCC; border-radius:4px;">Nominación: </span>
<select class="form-control" id="nom" name="id_juz_nom">
<option>Seleccione Nominación</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id_juz_nom']?>><?php echo $row['nominacion']?></option>
<?php } ?>
</select>


I've tried many methods such as this one and this other one. Without any success.

So, to be clear, what I need to do is: populate my second select with as many options as my MySQL query returns.

Answer

Change

data: { juz.value },

to

data: { juz },

and echo the HTML

as:

echo "<span class='input-group-addon' id='basic-addon1' style='border:solid 1px #CCC; border-radius:4px;'>Nominación: </span>
<select class='form-control' id='nom' name='id_juz_nom'>
<option>Seleccione Nominación</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value=<?php echo $row['id_juz_nom']?>><?php echo $row['nominacion']?></option>
<?php } ?>
</select>";