Laravel auth() is not working in ajax request - php

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

Related

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 : 419 unknown status with AJAX

I am requesting POST :
Route :
Route::post('/register','CommonController#postRegister')->name('register');
CSRF Meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
$("#submitSalonForm").click(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/register",
type: "post",
data: new FormData($('form')[1]),
cache: false,
contentType: false,
processData: false,
success:function(response) {
return alert('Form 2 submitted');
}
});
});
And the exception :
The exception comes sometimes and sometimes the code runs smoothly, I have no idea what am i missing here.
Change ajax method from post to get
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Ajx call:
let formData = $('form').serializeArray();
$.ajax({
url: "/register",
type: "POST",
data: {formData, "_token": $('#token').val()},
cache: false,
datatype: 'JSON',
processData: false,
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
Your route is get
Route::get('/register','CommonController#showRegister')->name('register');
Ajax call is making a post request, laravel sqwaks with a http exception.
EDIT:
Laravel 419 post error is usually related with api.php and token authorization
So try to include the token on ajax body instead like above.
In addition to putting the crsf-token value in the header meta tag you need to pass it through in your AJAX requests like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
No need to setup ajax separately. Laravel automatically generates a CSRF "token" for each active user session managed by the application. Get the token with this:
var token = "{{ csrf_token() }}";
Pass the token in data
var token = "{{ csrf_token() }}";
var formData = new FormData($('form')[1])
$.ajax({
url : '/register',
data : {_token:token,formData:formData},
type: 'post',
...
})
Well, I know I am too late, but I did face the exact issue you face.
I was 100% sure that the token has been sent with the request, but the issue is still.
So, after too many searches I finally got it fixed by following these steps:
php artisan config:clear
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan clear-compiled

AJAX request with laravel 5.2 error

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

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

Send Form for create with AJAX and Laravel 5.1

I'm developing an application with Laravel 5.1 and I have a problem when sending ajax petition I have the next code:
View for Create:
{!!Form::open()!!}
<div class="form-group">
{!!Form::label('genero','Genre:')!!}
{!!Form::text('genre',null,['id'=> 'genre','class'=>'form-control'])!!}
</div>
{!!link_to('#', $title = 'Create', $attributes = ['id'=> 'create','class'=>'btn btn-primary'], $secure = null)!!}
{!!Form::close()!!}
Ajax Petition:
$("#create").click(function(){
var genre = $("#genre").val();
var route = "http://localhost:8000/genre";
$.ajax({
url: route,
type: 'POST',
dataType: 'json'
data: {genre : genre}
});
})
In my Routes:
Route::resource('genre','GenreController');
But when send the petition I have the next error:
POST http://localhost:8000/genre 500 (Internal Server Error)
Thanks.
In default template , add meta tag
<meta name="_token" content="{!! csrf_token() !!}"/>
Then add script code :
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
Then you can use ajax call...as normal
My solution was the next code:
$("#registro").click(function(){
var data = $("#genre").val();
var route = "http://localhost:8000/genre";
var token = document.getElementById('token').value
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: {data : data}
});
});

Categories