$.ajax({
method: 'post',
url: '{{url("admin/append-course-pricebox-div")}}',
data: {_token:{{csrf_token()}},count:boxCount,workshop_id:$("#workshop_id").val()},
cache : false,
contentType: false,
processData: false,
success: function (result) {
if (result.status == 'success') {
$('#success').html('Details are saved successfully.');
$('#success_popup .cd-popup').addClass('is-visible');
}else if(result.status =='blankTerm'){
$("#php-error_includes").show().html(result.message);
}
$('#preLoader').hide();
},
error: function (errors) {
$('#preLoader').hide();
var error = (JSON.parse(errors.responseText));
$.each(error.errors, function (key, val) {
$('#php-error_'+key).html(val);
});
$('.php-error').show();
}
});
when I post request it shows error and Google says it because of csrf error how I pass csrf_token to the controller
please follow this steps
1."_token": "{{ csrf_token() }}", pass csrf token in request
2.<meta name="csrf-token" content="{{ csrf_token() }}">
3.Detailed explaination can be found hereenter link description here
Related
I have a form to create a card, this form is public, when a person fills out the form and wants to publish their card, they are asked to log in or if they are a new user to register.
I suppose that when the login is requested, the token that was immersed in the form expires and throws the 419 error.
How can I login and update the token to avoid error 419?
I am not an expert in Laravel so any suggestions would be appreciated.
reference diagram
here a part of the code that I have implemented
Login via AJAX
$(function () {
$('#login-form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var url = form.prop('action');
let data = form.serializeArray();
console.log(data);
$.ajax({
type: "post",
headers: {
Accept: "application/json",
},
url: url,
data: form.serializeArray(),
success: function(json) {
console.log('OK')
},
error: function(json) {
console.log('NOK')
alert(json);
},
});
});
});
Controller
public function __construct()
{
$this->middleware('create.card.newuser')->only('store');
$this->middleware('auth')->except(['create', 'store']);
}
Middleware "CreateCardIfNewUser"
public function handle(Request $request, Closure $next)
{
if (! Auth::user() )
{
return redirect()->route('digital_card.create')->with('openModalLogin', true)
->withInput($request->all());
}
return $next($request);
}
View 'layouts.app'
#if(session()->has('openModalLogin'))
<script>
$('#login-modal').modal({
show: true
});
</script>
#endif
Pass the csrf_token to the data:
…
data : {
_token: "{{ csrf_token() }}"
}
your error is due to the absence of csrf token. this solution is not only valid on this problem. each time you will have this problem of 419 then you must immediately think of the csrf token
data: {
_token: "{{ csrf_token() }}"
}
you must always add a csrf token to each submission otherwise you will always get this error
data: {
_token: "{{ csrf_token() }}"
},
I am A PHP developer and currently moving towards Laravel framework as per my task I have to complete the real-time table using ajax but I am sticking with an error which is CSRF token mismatch error please help me to resolve the error I am posting shortcode only
ajax
$(document).ready(function(){
$('.toggle-class').change(function() {
var status = $(this).prop('checked') === true;
var id = $(this).data('id');
var csrf=$('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
dataType: "json",
url: '/package/status',
data: {'status': status, 'id': id, 'XSRF-TOKEN': csrf},
success: function(data){
console.log('success '+data);
}
});
})
})
Route Path
Route::post('package/status', [App\Http\Controllers\PackageController::class,'status']);
Controller code
public function status(Request $request){
$Package = package::find($request->id);
$Package->status = $request->status;
$Package->save();
return response()->json(['success'=>'Status change successfully.']);
}
I don't know why it is showing me CSRF token mismatch when headers contain tokens once solved I can have some real-time action.
Try this:
data: {'status': status, 'id': id, '_token': '{{csrf_token()}}'},
<head>
.. .. ..
<meta name="csrf-token" content="{{ csrf_token() }}">
.. .. ..
</head>
Add this meta tag in the header of your master layout for csrf token which will be matched with the csrf token of your ajax call and thus it will solve your problem hopefully. Let me know if it works.
$.ajax({
type: "POST",
dataType: "json",
url: '/package/status',
data: {'status': status, 'id': id, '_token': '{{ csrf_token() }}'},
success: function(data){
console.log('success '+data);
}
});
Change XSRF-TOKEN to _token
And change data like this {{ csrf_token() }}
Just use _token for the csrf variable
$(document).ready(function(){
$('.toggle-class').change(function() {
var status = $(this).prop('checked') === true;
var id = $(this).data('id');
var csrf=$('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
dataType: "json",
url: '/package/status',
data: {'status': status, 'id': id, '_token': csrf},
success: function(data){
console.log('success '+data);
}
});
})
})
I want to pass the unlock key to route using ajax but I am not allowed to do so. The code gives me method not allowed error.
I cant see the error in my code, whether it the route error or some other error
<script>
$(document).ready(function(){
$('.result-container').hide();
$('.unlock-btn').on('click', function(){
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
});
});
</script>
So your route is a get but in ajax you are sending post request. Change it to post.
Route::post('/unlock', 'ThemeController#unlock')->name('unlock');
And also add a token in data otherwise you will get 419 error for missing CSRF.
$.ajax({
url: "{{route('unlock')}}",
method: 'post',
data: {
theme_id : {{$theme_id}},
key : $('.key').val(),
"_token": "{{ csrf_token() }}",
},
success: function(data){
console.log('success');
if(data === '0')
$('.result-container').show();
else
{
window.location = "{{route('view', ['theme_id' => $theme_id])}}";
}
}
})
I have a simple button who throw this Ajax request :
function myfunction(param){
var date_debut = $('#datet_debut').val();
var date_fin = $('#date_fin').val();
$.ajax({
url: '{{ route('createDispo') }}',
type: 'POST',
dataType: "json",
data: {
date_debut: name,
date_fin: name,
},
success: function (data) {
alert('success');
},
error: function (e) {
console.log(e.responseText);
}
});
}
But I have this error :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message
The route is generated like that :
Route::post('/createDispo','DepotDispoController#createDispo')->name('createDispo');
Here is the controller to handle the request :
public function createDispo(Request $request){
$user = User::find($request->user_id);
$disponibilite = new Disponibilite();
$disponibilite->date_debut = $request->date_debut;
$disponibilite->date_fin = $request->date_fin;
$user->disponibilites()->save($disponibilite);
}
So, why my Ajax request doesn't work ?
Remember to check that your method in the routes correspond to the method your are submiting.
Also, when submiting POST request Via Ajax you have to set the csrf token:
In your HTML header
<meta name="csrf-token" content="{{ csrf_token() }}">
Before ajax call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I'm using AJAX post request and sending with CSRF-TOKEN - on my local server worked well, but on my IIS SERV TokenMismatchException in VerifyCsrfToken.php line 67:
This is the code:
$.ajax({
url : '{{ route('dashboard.ajax.update') }}',
method : 'POST',
data : {
table : 'categories',
data : {
order: $count
},
conditions : {
id: $id
}
},
dataType: 'JSON',
headers : {
"X-CSRF-TOKEN": '{{ csrf_token() }}'
}
});
In the console I can see the request with: X-CSRF-TOKEN:w3liodqf8bdOvWH9uVTzLHVVsE0L1uIlCpnOyVVS
What can cause this problem?
$.ajax({
type: 'POST',
url: 'stringUrl',
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', '{{ csrf_token() }}');
},
data: {
'id': $id // etc..
},
cache: false,
error: function (xhr, type, exception) {
console.log("ajax error response type " + type);
}
});
Try to set it on "beforeSend" event
The problem was in my sessions. I've cleaned all my sessions files, cleaned the cache and used php artisan key:generate. After this - work pretty ok.