I am having trouble with an AJAX POST request in Laravel. when access my site first time, it's get older CSRF token from cache.
When i reload the site again, its get correct token. How can i solve this?
Put your token that way to ajax request:
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
Or set token in header:
<meta name="csrf-token" content="{{ csrf_token() }}" />
and then:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Good luck!
Related
Hi all I am having a problem when trying to split this code into a js file from the laravel page: php
In laravel page
$(".importer").click(function(e) {
// Stops the form from reloading
var parent = $('#parentdoc').val();
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
}
});
let fichiers_upload = new FormData();
let TotalFichiers = $('#fichiers-upload')[0].files.length; //Total Images
let images = $('#fichiers-upload')[0];
for (let i = 0; i < TotalFichiers; i++) {
fichiers_upload.append('images' + i, images.files[i]);
}
fichiers_upload.append('TotalFichiers', TotalFichiers);
fichiers_upload.append('idf', parent);
$.ajax({
url: "{{route('upload')}}",
type: 'POST',
contentType: false,
processData: false,
data: fichiers_upload,
success: function(result) {
$('#fichiers-upload').val("");
}
});
});
This works fine in the laravel page but if I create a js page to separate it from the laravel page
doing
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
I get this error
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/home/vol1_3/epizy.com/epiz_27528825/htdocs/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 369
message: "CSRF token mismatch." ```
First, the tag is wrong. This is for linking CSS:
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
What you want is a script element:
<script type="text/javascript" src="{{ asset('admin/import.js')}}"></script>
(I'm honestly surprised that even worked for you at all.)
More to the point of the error though, the literal string "{{ csrf_token() }}" is not the CSRF token. This is a placeholder which the server-side framework will replace with an actual value when rendering the page. But it doesn't do this for .js resources.
One approach could be to add that value to the page itself, perhaps somewhere in the <head> element:
<script type="text/javascript">
const csrf_token = "{{ csrf_token() }}";
</script>
As long as it's added before any other .js files are loaded, the window-level constant csrf_token would then be available to any of the other JavaScript code. Which you'd use in your AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': csrf_token
}
});
Alternatively, if you want you can just put the call to $.ajaxSetup itself in the page, after loading jQuery but before any of your AJAX calls, and then it can directly make use of the CSRF token placeholder. Either way works, it's a matter of personal preference.
Use Script tag instead of link tag to include your JS file:
<script src="{{ asset('admin/import.js')}}"></script>
Link tag is used to attach CSS files.
Try changing the token name to _token
headers: {
'_token': "{{ csrf_token() }}"
}
change :
<link rel="stylesheet" href="{{ asset('admin/import.js')}}">
to :
<script src="{{ asset('admin/import.js')}}"></script>
is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>
I am getting CSRF Token mismatch error while I am updating my page. I have included csrf token in both input hidden fields and as well as in ajax call..still getting the same error.
Here is my input
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
And i have included in my ajax call like this
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':qtype_subject_id,
'qtype_topic_id':qtype_topic_id,
'qtype_option':qtype_option,
'_token' : $('#token').val()
};
Still getting CSRF Token mismatch.
Add the csrf in your blade like this
<meta name="csrf-token" content="{{ csrf_token() }}">
And then write this line above your AJAX call or at the start of your JS file.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
And finally remove the token from the ajax calls and try.
remove this line '_token' : $('#token').val().
When I try the ajax in same page to html it works. Like this;
<html>
<head>
...
</head>
<body>
....
<script>
$.ajax({
url: /test/,
method: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: { name: a, surname: b},
dataType: 'json',
success: function (data) {
getList(data);
}
});
</script>
</body>
</html>
When I try the call same javascript as external. It doesn't work. Why?
<html>
<head>
...
</head>
<body>
....
<script src="{% static 'js/test.js' %}"></script>
</body>
</html>
Define the {{ csrf_token }} as a global variable in your HTML page in script tag as a global variable as such:-
var generated_csrf_token = "{{ csrf_token }}";
And then in your .js file call it,
headers: {'X-CSRFToken': generated_csrf_token},
But make sure you put AJAX call within the document ready func in $(document).ready(function () {***here***}
This way you can access it with name generated_csrf_token in any js file.
Hope this helps :-)
The csrf_token() changes when I use web middleware on the api routes.
api.php
Route::get('someroute/test', 'somecontroller')->middleware('web');
The controller
return response()->json([
'sent' => $request->header('token'),
'actual' => csrf_token()
]);
The token header comes from a meta tag that contains the csrf_token()
<meta id="csrf-token" content="{{ csrf_token() }}">
for some reason the token posted on the meta tag is different from the token on the server when I call the csrf_token() on the contoller.
Why is this crazy thing happening?