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:
- How To Install Ruby On Rails Server On Ubuntu
- Generate AJAX Loader Animated GIF Using AjaxLoad
- A Solution to Google Analytics “Tracking Unknown” problem
- How To Find Royalty Free Photos For Your Blog
- Autohotkey – Record and Repeat Keystrokes and mouse clicks
Leave your response!