i would like to know how in implement
dependent dropdown list laravel with Ajax
What I have tried:
<pre>iam getting the error in console :
jquery.min.js:5722
GET http:
send @ jquery.min.js:5722
ajax @ jquery.min.js:5383
(anonymous) @ ShippingPrices:503
dispatch @ jquery.min.js:2763
v.handle @ jquery.min.js:2647
handleMouseUp_ @ unknown
i would like to get Cities belong to selected Country and i have tried the following code: in Controller:
public function GetCities($CountryID)
{
$cities = City::where("CountryID", $CountryID)->orderby("CityName", 'CityID')->get();
return json_encode($cities);
}
Blade:
<div class="col-12">
<label class="form-label"
for="CountryName">{{ trans('shippingprices.CountryName') }}</label>
<div class="mb-1">
<select class="select2 form-select" id="CountryID" name="CountryID">
<option selected disabled>{{ trans('shippingprices.Choose') }}...</option>
@foreach ($countries as $countries)
<option value="{{ $countries->id }}">{{ $countries->CountryName }}
</option>
@endforeach
</select>
</div>
</div>
<div class="col-12">
<label class="form-label"
for="CityName">{{ trans('shippingprices.CityName') }}</label>
<div class="mb-1">
<select class="select2 form-select" id="CityID" name="CityID">
</select>
</div>
</div>
Ajax Code
<script src="{{ asset('assets/common-files/js/jquery.min.js') }}"></script>
<script type="text/javascript">
$(document).on('change', '#CountryID', function() {
var CountryID = $(this).val();
if (CountryID) {
$.ajax({
url: "{{ url('/ShippingPrices') }}/" + CountryID,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="CityID"]').html('');
var d = $('select[name="CityID"]').empty();
$.each(data, function(key, value) {
$('select[name="CityID"]').append(
'<option value="' + value.CityID + '">' + value
.CityName + '</option>');
});
},
});
} else {
alert('danger');
}
});
</script>
Route::get('/ShippingPrices/{CountryID}', [ShippingPriceController::class, 'GetCities']);