I am having trouble retrieving data from Controller using ajax this is my code
the trigger
<select id="course_select" name="course_select" class="form-control" required autofocus value="{{old('course_select')}}" onchange="getCourse()">
The my ajax section
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
type:'get',
url:'getCourseLessons/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
and my controller
public function getCourseLessons($id){
$lessons = DB::table('lessons')->select('id','Lesson_name')->where('course_id','=',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
Results console.log(data)
console.log(data)
ReferenceError: data is not defined[Learn More]
My Routes.
Route::get('/getcourselessons/{id}','AdminController@getCourseLessons');
I will appreciate all the help i can get.
First of all please check the route you used in Route/Web.php it should be like this
Route::get('getCourseLessons/{id}','YourController@getCourseLessons');
Check the controller.
public function getCourseLessons($id){
$lessons = \DB::table('lessons')->select('id','Lesson_name')->where('course_id',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
As per your ajax code is ook but you can try this also.
function getCourse(){
var id=$('#course_select').val();
alert(id);
$.ajax({
type:'get',
url:'{{url('getCourseLessons')}}/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
<select id="course_select" name="course_select" class="form-control" onchange="getCourse()">
<option>hi</option>
<option>hello</option>
</select>
It seems that there is problem in your select as the above code will output check the following
value="{{old('course_select')}}"
and one more thing I can't see CSRF
Add somewhere in your script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
try this bro change you url
or route
function getCourse(){
var id=document.getElementById('course_select').value;
var url = '{{ url('getCourseLessons/')}}/'+id;
alert(id);
$.ajax({
type:'get',
url:url,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
change your route
Route::get('getcourselessons/{id}','AdminController@getCourseLessons');
1- cheek your route
Route::get('/getCourseLessons/{id}','YourController@getCourseLessons');
2- change your Ajax attributes
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
url: '{{ url("getCourseLessons") }}',
type:'get',
datatype:'json',
data: {
"id": id,
"_token": "{{ csrf_token() }}"
},
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}