I want to return data from my database with .ajax()
but it throws out an error with the entire HTML of a page. Why is it doing that?
My .ajax()
call:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
route
Route::get('reports/groupsUsersGet',
array(
'as' =>'groupsUsersGet',
'uses' => 'ReportsController@groupsUsersGet'
)
);
view(form)
{{ Form::select('grup',$group,null,['class'=>'form-control','id'=>'group']) }}
controller
$term = Input::get('group_id');
$results = array();
DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json($results);
Also send the csrf_token()
as data.
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
_token: <?php echo csrf_token();?>,
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
It seems to me that you aren't sending CSRF token in the request, as @HikmatSijapati specified. In ajax request you can pass csrf token like this:
You could, for example, store the token in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Hope this helps!
Try this:
In your controller you can't define $queries
variable inside your method.
ajax call
$.ajax({
url: "{{ URL('reports/groupsUsersGet') }}",
method: 'GET',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
controller
$term = Input::get('group_id');
$results = array();
$queries = DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json(['results' => $results], 200);
Thank you everyone for your help but the error was in my not including use Response at the top of controller. When I did that it worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.