Home » Technology

ActionController Invalid Authenticity Token Solution For Using Ajax On Rails

27 July 2010 1 views No Comment Print This Post Print This Post Save Post As PdfDownload As PDF

The other day I was trying to run Ajax with Rails and a very simple pop-up invocation started failing when I used it with prototype.js. Basically I wanted that when a link object is clicked, it pops up a message from the browser using Ajax. Essentially <OnSuccess> was intended to create this pop-up which was not appearing.

So I changed <OnSuccess> to <OnFailure> to figure out the reason of failure and discovered the error [ActionController::InvalidAuthenticityToken] was causing the problem. This was strange since the non prototype.js counterpart code was working fine and the issue was seen only when I used prototype.js.

After multiple googling/hit and trial – the following solution seems to have worked for me.

Native code in the view file



<script src="/javascripts/prototype.js" type="text/javascript"> </script>
<p><a href="#" onclick="doAlert(  );">PopUp</a></p>
<script type="text/javascript">
 function doAlert(  ) {

  new Ajax.Request('/mycontroller/response', { onSuccess: function(request) { alert(request.responseText); }})
 }
</script>

Final code in the view file


<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<script src="/javascripts/prototype.js" type="text/javascript"> </script>
<p><a href="#" onclick="doAlert(  );">PopUp</a></p>
<script type="text/javascript">
 function doAlert(  ) {
  AUTOK = window._token;
  new Ajax.Request('/mycontroller/response'+'?authenticity_token='+AUTOK, { onSuccess: function(request) { alert(request.responseText); }})
 }
</script>

Notice that the changes added have been highlighted in bold. After making the above change, I see <OnSuccess> getting hit and the desired pop-up coming. Do try this solution if you are facing the same problem. If you think there is a better way of doing this, do update us in the comments section. If you liked the post, do share it with your friends.

Related posts:

  1. How To Install Ruby On Rails Server On Ubuntu
  2. Generate AJAX Loader Animated GIF Using AjaxLoad
  3. A Solution to Google Analytics “Tracking Unknown” problem
  4. How To Find Royalty Free Photos For Your Blog
  5. Autohotkey – Record and Repeat Keystrokes and mouse clicks

Leave your response!

Add your comment below

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree

Follow On Twitter
Follow On Facebook
Follow Using RSS
Follow Using Email
Tweet This Post
Share Post On Facebook
Digg This Post
Add To Delicious
Stumble Upon