I am trying to do a dynamic or dependent dropdown list but I don't know how to obtain data from the view depending on the data selected. I am trying to retrieve data from the controller with AJAX call and jQuery. Here is my code:
Route:
Route::controller('dropdowns', 'DropDownController');
Controller to retrieve data:
<?php
class DropDownController extends Controller {
public function postStations($id)
{
$stations = Station::where('basin_id', '=', $id);
$options = array('default' => 'Please select');
foreach ($stations as $station) {
$options += array($station->id => $station->value);
}
return Response::json($options);
}
}
?>
And the view:
@extends('layout')
@section('content')
<h1>Create new maintenance</h1>
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'maintenances')) }}
<div class="row">
<div class="large-9 columns">
{{ Form::label('basin_id', 'Conca') }}
{{ Form::select('basin_id', $basins) }}
</div>
</div>
<div class="row">
<div class="large-9 columns">
<label for="station_id">Estació</label>
<select id="station_id" name="station_id">
</select>
</div>
</div>
<div class="row">
<div class="small-6 columns">
{{ Form::submit('Create', array('class' => 'tiny button')) }}
</div>
</div>
{{ Form::close() }}
<script>
(function() {
$("#basin_id").change(function() {
$.getJSON("dropdowns/stations", $("#basin_id").val(), function(data) {
var $stations = $("#station_id");
$.each(data, function(index, value) {
$stations.append('<option value="' + index +'">' + value + '</option>');
});
});
});
});
</script>
@stop
The error is in the route, I should create parameter route like:
Route::get('dropdowns/stations/{id}', 'DropDownController@getStations');
And modify a bit the jquery script and DropDownController:
public function getStations($id)
{
$stations = Station::where('basin_id', '=', $id)->get();
$options = array();
foreach ($stations as $station) {
$options += array($station->id => $station->name);
}
return Response::json($options);
}
AJAX call:
<script type="text/javascript">
$(document).ready(function() {
$("#basin_id").change(function() {
$.getJSON("../dropdowns/stations/" + $("#basin_id").val(), function(data) {
var $stations = $("#station_id");
$stations.empty();
$.each(data, function(index, value) {
$stations.append('<option value="' + index +'">' + value + '</option>');
});
$("#station_id").trigger("change"); /* trigger next drop down list not in the example */
});
});
});
</script>
Why don't you use Select2 , it has ajax support and I use it in my projects as well.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community