How to insert a csrf token in Ajax request (jQuery method $.post())?


When you try to send data through the $.post() in the console an error is displayed

POST 405 Method not allowed

I understand that this is due to the fact that I didn't put in a request a csrf token?

And how to do it?

Thank you.

PS the Question is a little exposed in the documentation: but is not there for the $.post() and then a PostScript concerning the "By default, the resources/js/bootstrap.js file registers the value of the csrf-token meta tag with the HTTP library Axios. If you are not using this library, you will need to manually configure this behavior for your application." - it confuses me)) Maybe there are some really simple ways?
March 19th 20 at 09:27
2 answers
March 19th 20 at 09:29
In General, we have this (all working):

In HTML, ordered in accordance with the docks ( )

<meta name="csrf-token" content="{{ csrf_token() }}">

And in the script it looks like this:

 url: '/mypost',
 data: {'_token': $('meta[name="csrf-token"]').attr('content'), 'somefield': somevalue}
 }).done(function (data) { 
 alert('Successfully! '+ data); 

and Yes, it is IMPORTANT to:

the router should be spelled out

Route::post( ......

if there is, for example,

Route::put( ....

there will be an error.

Although, maybe you can make it work with PUT passing a value by analogy with the csrf token, but I already broke to experiment :D
In short, you actually copied the code from the docks and pass it off as revelation. - abbigail.Runolfss commented on March 19th 20 at 09:32
@abbigail.Runolfss, virtually all your comments on this resource - senseless flood. - Alexanne_Walker commented on March 19th 20 at 09:35
Can. Simply add _method = 'put' in the query. - alfonzo_Sauer21 commented on March 19th 20 at 09:38
Interestingly, in the dock described that wrote Crash XD but you did somehow differently :) - aric_Leffl commented on March 19th 20 at 09:41
March 19th 20 at 09:31
I do this:
In the main layout'e in the head add
<meta name="csrf-token" content="{{ csrf_token() }}">

In the footer add
the <script>
 headers: {
 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

The machine adding the csrf token to all future ajax requests.

Find more questions by tags Laravel