I need to create dinamic select into my form. I have wrote this code to get it dinamically from my controller (CodeIgniter) that get data from model.
This is the script:
<script type="text/javascript">
$(document).ready(function(){
$("select#regione").change(function(){
$.getJSON("http://test:8888/ricerca/test",{id: $(this).val()}, function(dati){
var options = '';
for (var i = 0; i < dati.length; i++) {
options += '<option value="' + dati[i].valore + '">' + dati[i].etichetta + '</option>';
}
$("#provincia").html(options);
$('#provincia option:first').attr('selected', 'selected');
});
});
});
</script>
This is the dropdown form:
<form action="base_url().'ricerca'" method="post">
<select name="regione" id="regione">
<option value="">No option</option>
<option value="Lombardia">Lombardia</option>
<option value="Lazio">Lazio</option>
</select>
<select name="provincia" id="provincia">
</select>
</form>
and this is the controller:
class Ricerca extends CI_Controller
{
public function test()
{
$dati = array();
array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
return json_encode($dati);
}
}
Before to do my query in the model I would see if my script works but if I select an option in the first select called "Regione" the script does nothing
you have to echo json data from controller function not to return data
public function test()
{
$dati = array();
array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
echo json_encode($dati);
}
or you can do
public function test()
{
$dati = array();
array_push($dati,array("valore"=>"ciao", "etichetta"=>"ciao"));
array_push($dati,array("valore"=>"mamma", "etichetta"=>"mamma"));
$this->output
->set_content_type('application/json')
->set_output(json_encode($dati));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.