Reputation: 1073
I have dropdown menu in template Laravel.
This is select list with names of countries.
I need to load cities in the closest dropdown menu after clicking by item of country.
So, I think it should be Ajax request to controller Laravel, that to get cities by id country.
Maybe there is any solution?
Upvotes: 0
Views: 1576
Reputation: 4526
You could do something like this in jQuery
<select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div id="response"></div>
The javascript, don't forget to put it inside $(document).ready()
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{csrf_token()}}'
}
});
$.ajax({
method: "POST",
url: "countriesList",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
And then in your Laravel Controller or directly from the route, you could return the countries and cities as multi-dimensional arrays
Route::post('countriesList', function() {
if(Request::ajax()) {
$country = Input::get('country');
$countryArr = [
"usa" => ["New York", "Los Angeles", "California"],
"india" => ["Mumbai", "New Delhi", "Bangalore"],
"uk" => ["London", "Manchester", "Liverpool"]
];
if($country !== 'Select'){
echo "<label>City:</label>";
echo "<select>";
foreach($countryArr[$country] as $value){
echo "<option>". $value . "</option>";
}
echo "</select>";
}
}
});
Upvotes: 2