Reputation: 193
I'm trying to build a dynamic dropdown list for countries and cities so:
I have the following view:
<div class="form-row">
<div class="col-sm-6">
<label>Pays</label>
<select class="form-control select2-single" data-width="100%"
name="pays" id="pays">
<option label=" "> </option>
@foreach($countries as $country)
<option data-id="{{$country->id}}" value="{{$country->name}}">
{{$country->name}}</option>
@endforeach
</select>
</div>
<div class="col-sm-6">
<label>Ville</label>
<select class="form-control select2-single" data-width="100%"
name="ville" id="ville">
</select>
</div>
</div>
And the following script :
<script type="text/javascript">
$(document).ready(function(){
$("#pays").change(function(){
/* let country_id = this.value;*/
let country_id = $(this).find("option:selected").data("id");
$.get('/getState?country='+country_id,function(data){
$("#ville").html(data);
});
});
/* });*/
</script>
And my controller:
public function getAllStates()
{
$country_id = request('country');
$states = State::where('country_id',$country_id)->get();
/* dd($states);*/
$option = "<option value = ''> Select State</option>";
foreach($states as $state){
$option.= '<option value = "'.$state->name.'">'.$state->name.'</option>';
}
return $option;
}
And the following route:
Route::group(['middleware' => ['auth','role:admin']], function() {
Route::get('/getState/{country}','App\Http\Controllers\CastingController@getAllStates');
});
The problem is the function getAllStates
isn't called, there is something wrong with my route?
Upvotes: 0
Views: 265
Reputation: 5715
Your script calls the route with a query parameter whereas the route is defined with a route segment.
So you have to change your JavaScript:
$(document).ready(function(){
$("#pays").change(function(){
/* let country_id = this.value;*/
let country_id = $(this).find("option:selected").data("id");
$.get('/getState/'+country_id,function(data){
$("#ville").html(data);
});
});
/* });*/
Upvotes: 1