TokenMismatchException on VerifyCsrfToken.php:53 - javascript

On laravel.log I get this:
[2020-08-20 15:51:08] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in /home/ialinves/public_html/cms/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:53
On browser console I get this:
POST https://ial.pt/ajaxform 500 (Internal Server Error)
My code is:
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var nom = 'teste';
$.ajax({
type: 'POST',
url: 'ajaxform',
data: /*JSON.stringify({name: nom})*/{},
//dataType: "json",
success: function (data) {
console.log(data);
}
});
});
On the head I have:
<meta name="csrf-token" content="{{ csrf_token() }}">
I've tried to comment csrf on Kernel.php and when I did it it worked...
I have also added route group to the route:
Route::group(['middleware' => 'web'], function () {
//Form routes
Route::post('ajaxform', 'formulariosController#contacts');
});

Related

405 (Method Not Allowed) on post method laravel ajax

I get an 405 (Method Not Allowed) error when sending an AJAX request. I've been working hard looking for a solution but still receive the same error.
I have added this inside the header section:
<meta name="csrf-token" content="{{ csrf_token() }}">
And this is the AJAX code:
function AjaxCall() {
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
header: {
'X-CSRF-TOKEN': token
},
data: {
_token: token,
_method: "PUT",
},
success: function() {
console.log('success');
}
});
}
Laravel code:
try {
$lastNum = DB::table('no_antrian')->select('antrian')->first();
if (!is_null($lastNum))
{
$data = DB::table('no_antrian')->update(['antrian' => $lastNum + 1]);
}
return response()->json(['success' => 'Sukses']);
}
catch(\Exception $e) {
return response()->json(['error' => 'failed']);
}
Route:
Route::post('antrian/insertNum', [AntrianController::class, 'getQueueNum']);
please Remove put method inside data
var token = $('meta[name="csrf-token"]').attr('content');
let myData = $('form').find('input[name="my_data"]').val();
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
data: {
_token: token,
my_data: myData
},
success: function() {
console.log('success');
}
});

Regenerate CSRF Token If ajax request has an error

I'm using ajax request to submit registration form. If a user submit form on first attempt with correct information, the request is working well. But If user made any mistake, correct the information and submit again, the data is inserted but in console.log(data), I'm facing this error:
"CSRF token mismatch."
"\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php".
Line: 389.
head.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
My Blade view:
$(document).ready(function() {
$('#send_form').click(function(e) {
e.preventDefault();
/*Ajax Request Header setup*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#send_form').html('Sending..');
/* Submit form data using ajax*/
$.ajax({
url: "{{ route('register')}}",
method: 'POST',
data: $('#ajax-register-form').serialize(),
success: function(response) {
$('#send_form').html('Submit');
document.getElementById("ajax-register-form").reset();
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
$('.error-warning').show();
}
});
});
});
If user has an error on first attempt, the csrf token should regenerate so user can submit the form without refreshing the whole page.
Remove headers from $.ajaxSetup and put it in send_form request like this.
$('#send_form').html('Sending..');
/* Submit form data using ajax*/
$.ajax({
url: "{{ route('register')}}",
method: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: $('#ajax-register-form').serialize(),
success: function(response) {
$('#send_form').html('Submit');
document.getElementById("ajax-register-form").reset();
},
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
$('.error-warning').show();
}
});
});

laravel ajax return 405

I'm trying to send data with ajax t controller and i get 405 error
Code
JS
$(document).ready(function(){
$('body').on('click', '.addbundlebutton', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
e.preventDefault();
var data= [];
$("input:checkbox[name=bundleProducts]:checked").each(function(){
data.push($(this).val());
});
// data are like ['41', '46'] in console //
$.ajax({
type: "post",
url: "{{ url('testadd-bundle') }}",
data: JSON.stringify(data),
success: function (data) {
console.log(data.success);
$(".addbundlebutton").remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
Route
Route::post('/add-bundle', 'frontend\BundleController#add');
Controller
public function add(Request $request){
//testing data...
$data = $request->all();
return response()->json($data);
}
Screenshot
Any idea?
You use this URL: url: "{{ url('testadd-bundle') }}",
But your route is set to be:
url('/add-bundle')
So try that instead. 405 means method not allowed, which means you try post on a get route for example.

Is it possible to insert data with ajax request by only using the csrf field instead of token?

I'm trying to insert data with CSRF field. I really don't have the idea of CSRF token. (new to laravel). I'm getting unknown status error in /classwork/insert.
//This is my ajax function: I really can't understand what is wrong with the code.
Is it possible to do ajax calls with only using {{csrf-field}}
function insertData(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
url: '/classwork/insert',
method: 'post',
data : 'data',
success:function(data){
console.log(data);
}
});
}
//This is my controller and Route:
public function insertTask(Request $request){
$task = new Task;
$task->task = $request->task;
$task->save();
}
//this is my route
Route::post('/classwork/insert', 'TaskController#insertTask');
Make a genric ajaxRequest function. Add this to meta
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in your global ajax function do this;
public function ajaxRequest(options){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: option.url,
method: option.method,
data : option.data,
success:function(data){
console.log(data);
}
});
}
Try using this way
Add this before ajax calling
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Please always add this meta tag in main blade page
<meta name="csrf-token" content="{{ csrf_token() }}">
And instead of old scholl jquery ajax.. just use Axios. simple and very easy. it already detect the csrd-token meta tag. so no need to do in the form or header
change this
$.ajax({
url: '/classwork/insert',
method: 'post',
data : 'data',
success:function(data){
console.log(data);
}
});
to this
axios.post('/classwork/insert', data)
.then(function(response) {
console.log(response);
});

AJAX Post request not working with Laravel

I can do this:
$.ajax({
type: "GET",
async: true,
url: '/someurl/',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Web:
Route::get('/someurl','MyController#myfunction');
And it works just fine, but when I try the same with post:
$.ajax({
type: "POST",
async: true,
url: '/someurl/',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
Route::post('/someurl','MyController#myfunction');
I get a 405 method not allowed error message in the console
POST using normal ajax need CSRF Token to be pass in POST Method
in your ajax
$.ajax({
type: "POST",
async: true,
url: '/someurl/',
dataType: 'json',
data : {"_token":"{{ csrf_token() }}"} //pass the CSRF_TOKEN()
success: function (data) {
console.log(data);
}
});
or
set head meta tag
<meta name="csrf_token" content="{{ csrf_token() }}" />
set header ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Add another route with
Route::post('/someurl','MyController#myfunction');
By the way u are not sending any data, in post we need to send data right..
Also check whether csrf token is being passed in data, if not as mentioned above try adding it manually.
If you are using {{Form...}} it would be automatically added to form data.

Categories