Laravel and ajax TokenMismatchException on delete request - php

I try to make delete request with ajax. Problem is that I always get TokenMismatchException even when I add X-CSRF-TOKEN to request header. So any ideas what I'm doing wrong? Here's my request
$('#confirm-delete').click(function () {
if(tableRowId !== -1) {
var obj = {
"X-CSRF-TOKEN": $('meta[name=csrf-token]').attr('content'),
id: tableRowId
};
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')},
url: 'sarasas/destroy',
method: 'DELETE', // Type of response and matches what we said in the route
data: obj,
success: function(response) { // What to do if we succeed
location.reload();
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
tableRowId = -1;
}
});

change this :
"X-CSRF-TOKEN": $('meta[name=csrf-token]').attr('content'),
to
"_token": $('meta[name=csrf-token]').attr('content'),
or if it's not working Add this JavaScript that sets defaults for all ajax request in jQuery. Preferably in a js file that is included across your app:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})

Add a meta tag with name csrf-token in view head section like,
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
.......
then add the following code in your JS file.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Related

405: Method Not Found on POST request

I am recieving the 405: Method not Found error when trying to perform a POST request on my laravel application. I'm trying to make a forum to learn how to use php and Laravel.
I am trying to post the request from /forum/category/{category}/post, I perform (almost) identical requests from just /forum and it works perfectly, so I assume it's something to do with this.
This is where I'm trying to post the request from (returns post.blade.php):
Route::get('forum/category/{category}/post', 'ForumController#showThreadPostForm');
The request:
var $form = $('form');
$form.submit((e) => {
e.preventDefault();
$.ajax({
type: "POST",
url: 'postthread',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')},
data: {"test": "data"},
success: function(res) {
window.location.reload();
console.log(res);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Error occured during AJAX request, error code: " + xhr.status);
},
});
});
The route:
Route::post('postthread', 'ForumController#postThread');
The controller method:
public function postThread(Request $request) {
//empty
}
I'm not sure if this information is enough.
Thanks.
I've used the same AJAX request on a different page /forum and it works, I'm not sure how to make it work on this page.
Try to add token to your data and add slash to your url.
also meta tag set to:
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajax({
type: "POST",
url: '/postthread',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf"]').attr('content')},
data: {"test": "data", "_token": $('meta[name="csrf"]').attr('content')},
success: function(res) {
window.location.reload();
console.log(res);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Error occured during AJAX request, error code: " + xhr.status);
},
});

How to fix Laravel HttpKernel\Exception error

I'm new to Laravel. I'm attempting a simple Ajax request however I get the following error message. What does this mean?
{message: "", exception:
"Symfony\Component\HttpKernel\Exception\HttpException",…} exception:
"Symfony\Component\HttpKernel\Exception\HttpException" file:
"C:\MAMP\htdocs\project_21_my_laravel_website\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 204 message: ""
index.blade.php
<div class="myTestLink">my Test Link</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".myTestLink").click(function(){
$.ajax({
method: 'post',
dataType: 'json',
url: 'insert-ajax',
success: function (data)
{
alert(data);
}
});
});
});
</script>
web.php
Route::post('/insert-ajax', 'myTestController#testingsomething');
myTestController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class myTestController extends Controller
{
public function testingsomething()
{
return "hello";
}
}
You must use CSRF token.
Please add the meta tag within the head tag in the blade file.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then change your javascript like this.
$(document).ready(function () {
$(".myTestLink").click(function(){
$.ajax({
method: 'post',
dataType: 'json',
url: 'insert-ajax',
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-token']").attr('content'));
},
success: function (data)
{
console.log(data)
}
});
});
}
Please add the meta tag within the head tag in the blade file.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in the scripts section please add the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
For reference you can go through this the documentation doc. Hope this helps and solves the issue. Thanks.

Laravel ajax post calls fails

I found several solutions to this one, tried them all (csrf tokens, urls..) but none of them seems to work.
This is my setup:
html file:
<meta name="csrf-token" content="{{ csrf_token() }}">
...
<button id="button" class="btn btn-success">Assign Selected</button>
...
My js file:
$(document).ready(function () {
$('#button').click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
dataType: 'json',
url: '/wptest',
data: { data: 'ahoj' }
}).done(function (data) {
console.log('Ajax was Successful!')
console.log(data)
}).fail(function () {
console.log('Ajax Failed')
});
});
}
And my web.php file:
Route::post('/wptest','UserController#assignToWP');
In my controller there is just a simple dd($request);
Edit: network tab shows: 200 OK
Problem: I always get Ajax Failed after button click. What do I miss?
Ok I found the solution:
The whole problem is, that in order for ajax to be successful, the controller needs to pass and return. dd function kills the controller before return and ajax fail therefore.
Make sure controller always gets to its return line.

Laravel 5.5 ajax call 419 (unknown status)

I do an ajax call but I keep getting this error:
419 (unknown status)
No idea what is causing this I saw on other posts it has to do something with csrf token but I have no form so I dont know how to fix this.
my call:
$('.company-selector li > a').click(function(e) {
e.preventDefault();
var companyId = $(this).data("company-id");
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
});
My route:
Route::post('fetch-company/{companyId}', 'HomeController#fetchCompany');
My controller method
/**
* Fetches a company
*
* #param $companyId
*
* #return array
*/
public function fetchCompany($companyId)
{
$company = Company::where('id', $companyId)->first();
return response()->json($company);
}
The ultimate goal is to display something from the response in a html element.
Use this in the head section:
<meta name="csrf-token" content="{{ csrf_token() }}">
and get the csrf token in ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Please refer Laravel Documentation csrf_token
Another way to resolve this is to use the _token field in ajax data and set the value of {{csrf_token()}} in blade. Here is a working code that I just tried at my end.
$.ajax({
type: "POST",
url: '/your_url',
data: { somefield: "Some field value", _token: '{{csrf_token()}}' },
success: function (data) {
console.log(data);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
});
It's possible your session domain does not match your app URL and/or the host being used to access the application.
1.) Check your .env file:
SESSION_DOMAIN=example.com
APP_URL=example.com
2.) Check config/session.php
Verify values to make sure they are correct.
This is similar to Kannan's answer. However, this fixes an issue where the token should not be sent to cross-domain sites. This will only set the header if it is a local request.
HTML:
<meta name="csrf-token" content="{{ csrf_token() }}">
JS:
$.ajaxSetup({
beforeSend: function(xhr, type) {
if (!type.crossDomain) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
},
});
use this in your page
<meta name="csrf-token" content="{{ csrf_token() }}">
and in your ajax used it in data:
_token: '{!! csrf_token() !!}',
that is:
$.ajax({
url: '/fetch-company/' + companyId,
dataType : 'json',
type: 'POST',
data: {
_token: '{!! csrf_token() !!}',
},
contentType: false,
processData: false,
success:function(response) {
console.log(response);
}
});
Thanks.
in my case i forgot to add csrf_token input to the submitted form.
so i did this
HTML:
<form class="form-material" id="myform">
...
<input type="file" name="l_img" id="l_img">
<input type="hidden" id="_token" value="{{ csrf_token() }}">
..
</form>
JS:
//setting containers
var _token = $('input#_token').val();
var l_img = $('input#l_img').val();
var formData = new FormData();
formData.append("_token", _token);
formData.append("l_img", $('#l_img')[0].files[0]);
if(!l_img) {
//do error if no image uploaded
return false;
}
else
{
$.ajax({
type: "POST",
url: "/my_url",
contentType: false,
processData: false,
dataType: "json",
data : formData,
beforeSend: function()
{
//do before send
},
success: function(data)
{
//do success
},
error: function(jqXhr, textStatus, errorThrown) //jqXHR, textStatus, errorThrown
{
if( jqXhr.status === "422" ) {
//do error
} else {
//do error
}
}
});
}
return false; //not to post the form physically
If you already done the above suggestions and still having the issue.
Make sure that the env variable:
SESSION_SECURE_COOKIE
Is set to false if you don't have a SSL certificate, like on local.
If you are loading .js from a file you have to set a variable with the csrf_token in your "main" .blade.php file where you are importing the .js and use the variable in your ajax call.
index.blade.php
...
...
<script src="{{ asset('js/anotherfile.js') }}"></script>
<script type="text/javascript">
var token = '{{ csrf_token() }}';
</script>
anotherfile.js
$.ajax({
url: 'yourUrl',
type: 'POST',
data: {
'_token': token
},
dataType: "json",
beforeSend:function(){
//do stuff
},
success: function(data) {
//do stuff
},
error: function(data) {
//do stuff
},
complete: function(){
//do stuff
}
});
Even though you have a csrf_token, if you are authenticate your controller actions using Laravel Policies you can have 419 response as well. In that case you should add necessary policy functions in your Policy class.
some refs =>
...
<head>
// CSRF for all ajax call
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
...
...
<script>
// CSRF for all ajax call
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content') } });
</script>
...
This worked for me:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
After this set regular AJAX call. Example:
$.ajax({
type:'POST',
url:'custom_url',
data:{name: "some name", password: "pass", email: "test#test.com"},
success:function(response){
// Log response
console.log(response);
}
});
You have to get the csrf token..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing same issue is rise ,Just Add this meta tag< meta name="csrf-token" content="{{ csrf_token() }}" >
After this also the error arise ,you can check the Ajax error. Then Also check the Ajax error
$.ajax({
url: 'some_unknown_page.html',
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
formData = new FormData();
formData.append('_token', "{{csrf_token()}}");
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
2019 Laravel Update, Never thought i will post this but for those developers like me using the browser fetch api on Laravel 5.8 and above. You have to pass your token via the headers parameter.
var _token = "{{ csrf_token }}";
fetch("{{url('add/new/comment')}}", {
method: 'POST',
headers: {
'X-CSRF-TOKEN': _token,
'Content-Type': 'application/json',
},
body: JSON.stringify(name, email, message, article_id)
}).then(r => {
return r.json();
}).then(results => {}).catch(err => console.log(err));
I had SESSION_SECURE_COOKIE set to true so my dev environment didn't work when logging in, so I added SESSION_SECURE_COOKIE=false
to my dev .env file and all works fine my mistake was changing the session.php file instead of adding the variable to the .env file.
just serialize the form data and get your problem solved.
data: $('#form_id').serialize(),
This error also happens if u forgot to include this, in your ajax submission request ( POST ),
contentType: false,
processData: false,
Got this error even though I had already been sending csrf token. Turned out there was no more space left on server.
This works great for those cases you don't require a form.
use this in header:
<meta name="csrf-token" content="{{ csrf_token() }}">
and this in your JavaScript code:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
}
});
A simple way to fixe a 419 unknown status on your console is to put this script inside in your FORM. {{ csrf_field() }}
in the name of the universe programmer
i send ajax with pure js and i understand when i dont set this method of ajax in pure js
<< xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") >>
i recive this error 419.
the full method of pure ajax is :
let token = document.querySelector('meta[name="csrf-token"]').content;
let xhr = new XMLHttpRequest();
// Open the connection
xhr.open("POST", "/seller/dashboard/get-restaurants");
// you have to set this line in the code (if you dont set you recive error 419):
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//* Set up a handler for when the task for the request is complete
xhr.onload = function () {
};
// Send the data.
xhr.send(`_token=${token}`);

How to fix 500 error in AJAX and Laravel 5?

I've been stuck with a 500 (internal server error) for a long time and I don't know why. I need to pass these codes later.
Blade
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('#addChirp').submit(function() {
var msg = $('#message').val();
console.log(msg);
var dataString = "message="+msg;
console.log(dataString);
$.ajax({
type: "POST",
url: "post",
data: dataString,
success: function(data) {
console.log(data);
$('#showData').html(data);
},
error: function(data) {
alert("fail");
}
});
});
});
Routes
Route::post('post', function() {
if(Request::ajax()) {
return var_dump(Response::json(Request::all()));
}
});
Try calling Request and Response as a global facade following
Route::post('post', function() {
if(\Request::ajax()) {
return var_dump(\Response::json(\Request::all()));
}
});
If that does not work can you please update your question with full ajax response so problem can be narrowed down?
I think you havn't added any meta value in your head tag of html like
<meta name="csrf_token" content="{{ csrf_token() }}" />
If csrf tag exist than try modify your jax call.
X-CSRF-TOKEN': $('input[name="_token"]').value()
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls

Categories