Laravel and AJAX doesn't return anything - php

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.

Related

Getting 500 Internal issue during ajax response

I am struggling with this code. I am unable to send a response with ajax.
Ajax script is here.
$(document).ready(function () {
$('#selectSize').change(function () {
var idSize = $(this).val();
$.ajax({
type: "get",
dataType: 'json',
url: 'getproductprice',
data: {
idSize: idSize
},
success: function (response) {
console.log("working");
},
error: function () {
console.log("error");
}
});
});
});
Here is the Blade markup
<select name="size" id="selectSize" style="width:150px;">
<option value="">Select Size</option>
#foreach($productDetails->attributes as $size)
<option value="{{$productDetails->id}}-{{$size->size}}">{{$size->size}}</option>
#endforeach
</select>
And here is the controller code
public function getProductPrice(Request $request)
{
$data = $request->all();
$proArr = explode("-", $data['idsize']);
$proAttr = ProductsAttribute::where(['product_id' => $proArr[0], 'size' => $proArr[1]])->first();
$getCurrencyRates = Product::getCurrencyRates($proAttr->price);
echo $proAttr->price . "-" . $getCurrencyRates['USD_Rate'] . "-" . $getCurrencyRates['GBP_Rate'] . "-" . $getCurrencyRates['EUR_Rate'];
echo "#";
echo $proAttr->stock;
}
I do not know, What I am doing wrong .when I select option value.
error will come like.
"Trying to get property 'image' of non-object (View:
C:\xampp\htdocs\wrost\resources\views\shop\product-details.blade.php)"
Your ajax should be -
$.ajax({
url: 'getproductprice',
type: 'POST',
data: {idSize: idSize},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
alert("Something Went Wrong, Please check again");
}
});
First make sure you add meta tag for csrf in your head
<meta name="csrf-token" content="{{ csrf_token() }}">
At last you need to add header object in your ajax object
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
it will be like this
$.ajax({
type: "get",
dataType : 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:'getproductprice',
data: {idSize: idSize},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});

Can't check if request is ajax with $request->ajax() and Laravel 5.4

I have a problem trying to check if a request is ajax. This is my code:
Route
Route::post('cookies-alert', 'CookiesController#weUseCookies')->name('cookies.weuse');
Controller
namespace app\Http\Controllers;
use Illuminate\Http\Request;
class CookiesController extends Controller
{
public function weUseCookies(Request $request)
{
if($request->ajax()){
return response()->json(['status' => 'successful']);
}else{
return response()->json(['status' => 'error']);
}
}
}
The form (with Laravel collective, it auto create the _token)
{{ Form::open(['route' => ['cookies.weuse', ''], 'method' => 'POST', 'id' => 'cookie-form']) }}
....
<button type="submit">Ok</button>
{{ Form::close() }}
And the js
$('#cookie-form').on('submit', function(e){
e.preventDefault();
// .....
$.ajax({
url: url,
method: 'POST',
dataType: 'JSON',
data: data
}).done( function (response) {
var res = response;
if( res.status == 'successful' ){
console.log(res.status);
}else{
showError('error :(');
}
});
});
i tried with this other way
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'JSON',
success: function (data) {
console.log(data);
}
});
and using jquery 3.2.1 from https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
But it always return "error" from my controller.
I also tried to use Request::ajax() like this but it jump the if{} and go to the else{} option from my controller.
What am i doing wrong?
My code works on local but not on the server
laravel uses X-Requested-With http header to check if the incoming request is an ajax or not also you have to add #csrf field to your form :
$.ajax({
url: url,
type: 'POST',
// add _token field for csrf protection
data: {
_token : ''
},
dataType: 'JSON',
// add x-forwarded-with also add X-CSRF-TOKEN header for csrf protection
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': ..,
}
});
or you can use axios because laravel works better with it :
axios({
method: 'POST',
url: 'url',
data: {
_token: 'token',
},
responseType: 'json',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': 'token,
}
}
Request::wantsJson()
It's working with axios as well.
you need set header like bellow in app.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Vue = require('vue');
$request->wantsJson() works well with axios on laravel 8.

Unable to get the response from ajax call in yii2

I have a GirdView which includes checkbox. Now I have a button which i routed to another action controller. Below is my code
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'id'=>'grid',
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'Meter Serial Number',
'Issued To',
'Store',
],
]); ?>
Set PDF
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.post({
url: 'ogpheader/viewsetpdf',
dataType: 'json',
data:{keylist: keys},
success:function(data) {
alert('Done')
}
});
}) });
Then in my controller
public function actionViewsetpdf()
{
/*$model = $this->findModel($id);
print_r($model);*/
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
exit();
}
When I click on the button i get empty view. I followed this tutorialI don't know what is the problem. I am stuck to it.
Update1
While checking it in network
Update 2
As suggested I have tried with $.ajax and below is the result
Update 3
After changing the JS
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?= URL::toRoute(["ogpheader/viewsetpdf"])?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
The result is
Any help would be highly appreciated.
Change the controller and see what return, probably csrf token missing that why you got empty output
public function actionViewsetpdf()
{
if(isset($_POST['keylist']))
{
$keys = json_decode($_POST['keylist']);
print_r($keys);
}
else{
echo 'no data';
}
exit();
}
POST method required csrf token so you have to pass _csrf token as a parameter
$.ajax({
url: 'ogpheader/viewsetpdf',
type: 'post',
dataType: 'json',
data: {
keylist: keys,
_csrf: '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function(data) {
console.log(data);
}
});
Or you can disable csrf valdation by adding this to your controller
public function beforeAction()
{
if ($this->action->id == 'viewsetpdf') {
Yii::$app->controller->enableCsrfValidation = false;
}
return true;
}
Or simplest way just change POST to GET
$.post() has limited parameter to pass. Use $.ajax(). Also you need to add e.preventDefault() to stop redirection from a tag
$(document).ready(function () {
$('#myid').click(function(e) {
e.preventDefault();
var keys = $('#grid').yiiGridView('getSelectedRows');
// alert(keys);
$.ajax({
url: '<?php echo URL::toRoute(["ogpheader/viewsetpdf"]); ?>',
dataType: 'json',
data:{keylist: keys},
type: 'post',
success:function(data) {
alert('Done')
}
});
}) });
Use below js
<?php
$url = Url::toRoute(['ogpheader/viewsetpdf']);
$this->registerJs(<<< JS
$(document).ready(function () {
$('#myid').click(function() {
var keys = $('#grid').yiiGridView('getSelectedRows');
$.ajax({
url: '$url',
data: {keylist: keys},
type: "POST",
dataType: 'json',
success:function(data) {
alert('Done');
}
});
});
});
JS
); ?>

Laravel 5.5 delete item with ajax call on click

I am trying to delete a model item via an ajax call when you click on an icon.
Without an ajax call and just with a form everything works great.
This exception is thrown when I look in my network tab of my chrome dev tools
"Symfony\Component\HttpKernel\Exception\HttpException"
This is my icon:
<i class="fa fa-trash-o deletebtn" aria-hidden="true" data-pointid="<?php echo $damagePoint->id ?>"></i>
My ajax call:
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
type: 'delete',
success: function (response) {
}
});
})
My route:
Route::delete('pointdelete/{id}', 'DamagePointController#delete');
My controller method
public function delete($id)
{
$todo = DamagePoint::findOrFail($id);
$todo->delete();
return back();
}
if you are using delete route is like similar to post.Here is the sample code.you can change as per your need
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
type: 'DELETE',
url: '/pointdelete',
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: {id:pointid,"_token": "{{ csrf_token() }}"},
success: function (data) {
alert('success');
},
error: function (data) {
alert(data);
}
});
});
Route
Route::delete('pointdelete','DamagePointController#delete');
controller
public function delete(Request $request){
if(isset($request->id)){
$todo = DamagePoint::findOrFail($request->id);
$todo->delete();
return 'success';
}
}
Please check below code:
Route::delete('pointdelete',['as' => 'point.delete','uses' => 'DamagePointController#delete']);
<button class="fa fa-trash-o deletebtn" aria-hidden="true" onclick="delete({{ $damagePoint->id }}"></button>
<script type="text/javascript">
function delete(id){
var _token = "{{ csrf_token() }}";
$.ajax({
url : "{{URL::route('your-delete-route')}}",
type : 'delete',
dataType : 'json',
data : {
'id': id,
'_token':_token
},
beforeSend : function() {
},
complete : function() {
},
success : function(resp)
{
console.log(resp);
}
});
}
</script>
public function delete(Request $request,$id)
{
DamagePoint::destroy($id);
return response()->json(['success' => true],200);
}
Try this kind of ajax call
$(".deletebtn").click(function(ev){
let pointid = $(this).attr("data-pointid");
$.ajax({
url: '/pointdelete/' + pointid,
data : {'_method':'delete','_token':'your csrf token'},
//type: 'delete',
type:'post',
success: function (response) {
}
});
})
Also, verify that what URL is called in request header information in your chrome developer tools.
you just don't need a form try to put your token as {{ csrf_token() }} in ajax.
Recently I got the same error and none of above solutions worked for me in laravel 5.7
I had code something like -
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});
Then I had to set csrf token first using setup method - changed code is something like -
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
async: false,
url:validUrl,
data:{id:1},
success:function(response){
if(response && response.error) {
//show error
} else {
// success
}
}
});

Assign Ajax response to php variable

How do I assign my ajax response to a php variable, if it is even possible?
In my Laravel controller I have this method for that purpose:
public function editProductPost(Request $request)
{
return response()->json([
'sliderValue' => $request->get('value')
]);
}
And this is my Ajax:
/**
* Ajax Post
*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
contentType: "application/json",
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: JSON.stringify({
value: getSliderVal,
productId : getPrId
}),
datatype: 'json',
success: function(response) {
// get response
console.log(response.sliderValue)
}
If I understand you correctly, you want to do something like this:
public function editProductPost(Request $request)
{
// Create your JSON response
$response = response()->json([
'sliderValue' => $request->get('value')
]);
// Assign the content of the response to a variable
$responseContent = $response->content();
// Return your response
return $response;
}

Categories