R
R
Roman2019-03-31 21:44:49
Laravel
Roman, 2019-03-31 21:44:49

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

Hello.
When I try to send data via the $.post() method, the error
POST 405 Method not allowed is displayed in the console
, as I understand it, this is due to the fact that I did not insert the csrf token into the request?
But how to do it?
Thank you.
PS The question is a little covered in the documentation: https://laravel.com/docs/5.8/csrf#csrf-x-csrf-token but there is no for the $.post() method and then the postscript regarding "By default, the resources/ js/bootstrap.js file registers the value of the csrf-token meta tag with the Axios HTTP library. - confuses me)) Maybe there are some very simple ways?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2019-03-31
@procode

In general, it turned out like this (everything works): I
registered it in HTML in accordance with the docs ( https://laravel.com/docs/5.8/csrf#csrf-x-csrf-token )
And in a script it looks like this:

$.post({
    url: '/mypost',
    data: {'_token': $('meta[name="csrf-token"]').attr('content'), 'somefield': somevalue}
    }).done(function (data) {		
    alert('Успешно! ' + data);		
  });

and yes, IMPORTANT: Route::post( ...... if there, for example, Route::put( .... - there will
be an error. Although, it can and can be made to work with PUT by passing the value by analogy with csrf-token, but I'm already breaking to experiment :D

C
Crash XD, 2019-04-02
@crashxd

I do like this:
In the main layout, in the head I add
In the footer I add

<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>

Thus automatically adding the csrf token to all future ajax requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question