ActionController Invalid Authenticity Token Solution For Using Ajax On Rails

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. Rails – Private Method `gsub!’ called for – Solution
  2. How To Install Ruby On Rails Server On Ubuntu
  3. Generate AJAX Loader Animated GIF Using AjaxLoad
  4. A Solution to Google Analytics “Tracking Unknown” problem
  5. WordPress Missed Schedule Solution

Inficone runs on the Genesis Framework

Genesis Framework
Genesis empowers you to quickly and easily build incredible websites with WordPress. Whether you're a novice or advanced developer, Genesis provides the secure and search-engine-optimized foundation that takes WordPress to places you never thought it could go. It's that simple - start using Genesis now!
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

Speak Your Mind

*

Spam Protection by WP-SpamFree