Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to send an Authenticity Token with AJAX to Rails

This works but gets stopped because it lacks an authenticity token:

$(".ajax-referral").click(function(){   $.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script"});   return false; }); 

So I tried adding it like so:

$(".ajax-referral").click(function(){   $.ajax({type: "POST", url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN, dataType: "script"});   return false; }); 

And it passes the auth_token correctly as a param, but seems to lose the rest of my form.

Anyways to accomplish both sending the form data that works, and the authenticity token as well?

This is a rails environment. And I have this in my head.

= javascript_tag "var AUTH_TOKEN = '#{form_authenticity_token}';" if protect_against_forgery? 

Things I've tried

1.

= hidden_field :authenticity_token, :value => form_authenticity_token 

2.

$.ajax({type: "POST", url: $(this).parent("form").attr("action"), dataType: "script", authenticity_token: AUTH_TOKEN}); 

3.

// Always send the authenticity_token with ajax $(document).ajaxSend(function(event, request, settings) {     if ( settings.type != 'GET' ) {         settings.data = (settings.data ? settings.data + "&" : "")             + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );     } }); 
like image 856
Trip Avatar asked Sep 26 '11 20:09

Trip


People also ask

How does authenticity token work in Rails?

When the user submits the form, Rails looks for the authenticity_token , compares it to the one stored in the session, and if they match the request is allowed to continue. Since the authenticity token is stored in the session, the client cannot know its value.

How Rails send data using Ajax?

Use rails-ujs (no jQuery) Making an AJAX POST call with rails-ujs looks identical to making it with jQuery: Rails. ajax({ type: "POST", url: "/things", data: mydata, success: function(repsonse){...}, error: function(repsonse){...} })

How do I add AJAX in Rails?

In Rails, submitting an AJAX request can be done as easily as adding remote: true to a link, button, or form. From there you can have any response be some JavaScript code waiting on the server side, and it will execute in the client's browser. Here's the simplest code example of UJS via AJAX in a link.


2 Answers

Actually, you are reading the action attribute of form and sending a post ajax request to it. to send form data you have to submit the form or you can serialize the form data and send it in ajax request like

$(".ajax-referral").click(function(){   $.ajax({       type: "POST",        url: $(this).parent("form").attr("action") + "?&authenticity_token=" + AUTH_TOKEN,        data:$(this).parent("form").serialize(),       dataType: "script"       });   return false; }); 

Doing this will serialize your form data and send it along with ajax request and authenticity token is already being sent via query string

like image 127
Muhammad Adeel Zahid Avatar answered Sep 21 '22 23:09

Muhammad Adeel Zahid


This token also already appears in one of the "meta" tags in the head of the application.html.erb layout file by default if you have the following ERB at the top:

<%= csrf_meta_tag %> 

That ERB roughly renders to:

<meta content="abc123blahblahauthenticitytoken" name="csrf-token"> 

You can then grab it using jQuery with the following code:

var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content'); 
like image 23
omdel Avatar answered Sep 20 '22 23:09

omdel