webpack jquery ajax rails 5 InvalidAuthenticityToken
Asked Answered
T

1

8

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?

Thomajan answered 22/7, 2017 at 5:42 Comment(0)
A
16

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) {
   ...
  }
});
Acquiescent answered 25/7, 2017 at 21:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.