I have some javascript making an ajax call in my Rails site:
$.ajax({type: 'PUT', url: url, data: { dummy: data }, complete: function(data) {}});
When Rails gets it, it throws back an ActionController::InvalidAuthenticityToken Error. I’d like to keep the protect_from_forgery stuff in there, if possible… But I’m at a loss for how can I pass the auth token from a javascript file?
Can anyone help me out?
In your layout, add this before any other JS runs:
authTokenis coded as a function so that it’s less likely you’ll accidentally overwrite it with other JavaScript.Alternatively, as of Rails 3, the auth token is embedded as a
<meta>tag, which you can read with:In your main JS, you can then call
authToken(), and it’ll return your authenticity token as a string to include in your Ajax calls. For example, using jQuery:Note that if you use Rails’ built-in
form_forhelper, it automatically adds the authenticity token in a hidden input. If you want to send all of the form’s data, including the hidden auth token, you can simply use:This pattern is often useful when you’ve already written a form that works without JS, and you’re adding an unobtrusive layer of JS that simply sends the form’s data via Ajax.