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?
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) {
   ...
  }
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With