In my application i am using Ajax request but it is giving me jquery-3.3.1.js:9600 POST http://localhost:8000/get_types_ajax
gettin 419 (unknown status)
My javascript is:
$(document).ready(function() {
var ckbox = $("input[name='particulars']");
var chkId = '';
$("input[name='particulars']").on('change', function() {
if (ckbox.is(':checked')) {
values = [];
names = [];
$("input[name='particulars']:checked").each ( function() {
amount = $(this).val().split(",");
console.log("amount",amount);
values.push(amount[0]);
names.push(amount[1]);
});//checked
total_value = 0;
values.forEach(function(value) {
value = Number(value);
total_value = total_value + value;
document.getElementById('total').innerHTML = total_value;
});//foreach
}//if
else {
total_value = 0;
document.getElementById('total').innerHTML = total_value;
}
$.ajax({ url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
my web.php is :
Route::post('/get_types_ajax', 'DevkrutyaController#get_types');
The 419 error you are getting is due to the missing CSRF token in your ajax request. To pass a csrf token you can use ajax setup method of jquery
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax({
url:"{{url('/get_types_ajax')}}",
type: 'POST',
data: {message:names},
success: function (data)
{
console.log(data);
}
});
});//onchange
});//ready
For more information https://laravel.com/docs/master/csrf#csrf-x-csrf-token
i see.You don't pass CSRF_TOKEN WITH Post Request
if your are using post method then u must pass CSRF_TOKEN with that other wise you can ignore(skip) some Url in VerifyCSRF token middleware
protected $except = [
'stripe/*',
];
other wise add this line in your js file it will automatically send
csrf token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
for more detail read this article
Laravel uses CSRF token to protect your application from cross-site request forgery (CSRF) attacks. You will need to pass the CSRF token in your ajax.
In header
<meta name="csrf-token" content="{{ csrf_token() }}" />
In script
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
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 have a problem in ajax request in laravel 5.8
The problem
POST http://dailyshop.test/ajaxRequest 419 (unknown status)
The route
Route::get('ajaxRequest', 'FrontEndController#ajaxRequest');
Ajax Code
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#add-to-cart').click( function(e) {
e.preventDefault();
var product_id = $(this).data('id');
var url = "{{ route('addToCart') }}";
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{product_id:product_id},
success:function(data){
alert(data.success);
}
});
});
});
The function
public function ajaxRequest() {
dd('Yes! it working !');
return view('ajaxRequest');
}
I am trying to add an ajax call that changes the status of a listing, between listed and unlisted, when submitting the form I am having a 403 forbidden error in the console of the browser, I made some checking and it appears that Django is forbidding the form because of a lack of csrf token, however I am not good in javascript, so any help would be appreciated.
Here is my code in my view:
#require_POST
#ajax_required
#login_required
def unlist_ajax(request):
pk = request.POST.get('pk', None)
is_visible = request.POST.get('is_visible', None)
if pk and is_visible:
listing = get_object_or_404(Listing, pk=pk)
if is_visible == 'true':
listing.is_visible = False
listing.save()
messages.success(request, _("Listing unlisted"))
return JsonResponse({'status': 'ok'})
else:
listing.is_visible = True
listing.save()
messages.success(request, _("Listing re-listed"))
return JsonResponse({'status':'ok'})
and here is the template script:
in the top of the template, in the header:
<script>
function unlistPostAjax(listing_id, is_visible) {
var confirmation = confirm("{% trans 'are you sure you want to change the status of your listing?' %}");
if (confirmation) {
$.post("{% url 'dashboard:unlist_ajax' %}", {pk: listing_id, is_visible: is_visible}, function (response) {
console.log('sending delete query'); location.reload();
})
}
}
</script>
and in the bottom of the body:
<script src="{% static 'js/jquery.cookie.js' %}"> </script>
<script>
$(document).ready(function () {
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod (method) {
// These HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
// Set X-CSRFToken HTTP Header
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
</script>
You can add this to the top of your <script> or if you have a base html template you can put this in there too.
{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
</script>
Believe you just need to add the csrf above the script you defined, but this is the whole implementation I currently use. I have no issues.
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')
}
});