AJAX request with laravel 5.2 error - php

I have this ajax request in home.blade.php :
function send(event) {
event.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')},
type: "POST",
url: "{{ route('add_action') }}",
data: {name: $("#name").val(), niceness: $("#niceness").val(), _token: "{{ Session::token() }}"}
});
}
in the controller I have this postAction:
public function postInsertNiceAction(Request $request)
{
$this->validate($request, [
'name' => 'required|alpha|unique:nice_actions',
'niceness' => 'required|numeric',
]);
$action = new NiceAction();
$action->name = ucfirst(strtolower($request['name']));
$action->niceness = $request['niceness'];
$action->save();
$actions = NiceAction:: all();
if ($request->ajax()) {
return response()->json();
}
return redirect()->route('home');
}
I added this meta tag:
<meta name="_token" content="{{ csrf_token() }}">
so when I run this I got this error :
jquery-1.12.0.min.js:4 POST http://localhost:8000/do/add_action 422 (Unprocessable Entity)
I tried to change the version of the jQuery file but it's not working.
Any help will be appreciated!
I'm new to Laravel.
Thank you

Try this:
function send(event) {
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
$.ajax({
type: "POST",
url: "{{ route('add_action') }}",
data: { name: $("#name").val(), niceness: $("#niceness").val() },
});

Related

Laravel auth() is not working in ajax request

I put my route under auth middleware group and also passed the csrf token in the header and but after all this, I am still getting 'Unauthenticated' message. But this error message only comes in the live server and firefox browser and it's working nicely in my local server and chrome browser.
Here is my route
Route::middleware(['middleware' => 'auth'])->group(function () {
Route::get('/test', [TestController::class, 'getTest']);
})
My ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}",
Accept: "application/json",
"Content-Type": "application/json"
}
});
$.ajax({
url: "{{ url('/test') }}",
type: "get",
data: {
id: {{ auth()->user()->id }}
},
success: function(response) {
var data = JSON.parse(response)
}
})
And my controller
$user = auth()->user();

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.

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
}
}
});

How to use POST method in laravel and ajax

When I use a POST method with the following ajax request, it throws a "Method not allowed" error. If I use the form POST without using ajax, it goes to the proper method.
In Router.php:
$this->post('TestPost','DashboardController#TestPostMethod');
In View, the ajax request is:
$.ajax(
{
type: "POST",
url: 'TestPost',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert('hid post');
SetHotandWorstData(data,'hotquantity');
},
error: function (msg) {
alert('error');
alert(msg.responseText);
}
});
In Controller:
function TestPostMethod(Request $request)
{
$hotworstsalesdata = DB::table('100_INVOICEDETAIL')
->select( '100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME',
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt'))
->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME')
->orderBy('salesqty')
->take(10)
->get();
return Datatables::of($hotworstsalesdata)->make(true);
}
you should pass "_token" in POST data. Laravel use token for cross-site request forgery (CSRF) attacks. use following code in your AJAX request
data: { _token: "{{ csrf_token() }}" }
Updated answer:
I have re-create same scenario on my system with laravel 5.4 and it's working for me.
my route (web.php) code is:
Route::post('/test_post', 'DashboardController#getData');
Javascript code is:
<script type="text/javascript">
$.ajax({
type: "POST",
url: '{{ url('/') }}/test_post',
data: { _token: "{{ csrf_token() }}" },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
console.log(data);
},
error: function (msg) {
console.log(msg.responseText);
}
});
</script>
DashboardController file is:
public function getData(Request $request) {
print_r($request);
}
Recently I got error with DELETE method ! I fixed by setting csrf token in html header and get in ajax . Hope this can solve your problem ..
<html>
<header>
<meta name="csrf-token" content="{{ csrf_token() }}" />
In ajax,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Laravel and AJAX doesn't return anything

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.

Categories