Reputation: 1523
can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax. i have done it without ajax, but i don't know how to do with ajax. without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
@foreach($nations as $nations)
<option value="{{@$nation_id}}" {{@$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{@$nations->nation}}</option>
@endforeach
Controller:
$nations = nation::all();
Upvotes: 1
Views: 7929
Reputation: 387
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
@foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
@endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController@getTeacher');
Hope this will work..
Good Luck...
Upvotes: 3
Reputation: 719
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController@method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>
Upvotes: 0