Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webpack jquery ajax rails 5 InvalidAuthenticityToken

I use Rails 5.1 + webpack When I include jQuery to my project with

 plugins: [
    new webpack.ProvidePlugin({
        'jQuery': 'jquery',
        '$': 'jquery',
        'global.jQuery': 'jquery'
    })
  ]

And try to use jQuery.ajax PUT, POST, or DELETE requests e.g.

var that = this;
$.ajax({
  url: navigator_item.url,
  method: 'DELETE',
  success: function(res) {
   ...
  }
});

I get ActionController::InvalidAuthenticityToken.

But, when I include jQuery with next line in app.js file

import $ from 'jquery'
window.jQuery = $;
window.$ = $; // lazy fix if you want to use jQuery in your inline scripts.

and this in shared.js

module.exports = {
  resolve: {
    alias: {
        'jquery': 'jquery/src/jquery'
    }
  }

jQuery.ajax works fine.

Is there a way using jQuery.ajax when you include jQuery as a plugin?

like image 568
Stanley Shauro Avatar asked Jul 22 '17 05:07

Stanley Shauro


1 Answers

The ActionController::InvalidAuthenticityToken has nothing to do with jQuery.

You have to pass an authenticity_token parameter with all your PUT, POST and DELETE requests.

To do that you can usually fetch it from the header with $('[name="csrf-token"]')[0].content

So your request would look something like:

var that = this;
$.ajax({
  url: navigator_item.url,
  data: { authenticity_token: $('[name="csrf-token"]')[0].content},
  method: 'DELETE',
  success: function(res) {
   ...
  }
});
like image 189
Kkulikovskis Avatar answered Oct 13 '22 01:10

Kkulikovskis