Siddharth Siddharth - 2 years ago 130
jQuery Question

401 Unauthorized when calling .ajax method in rails 3 application

I'm passing a ajax call to update data in my application through twitter bootstrap modal window. The ajax code is given below:

var link=$('#link_hash').val();
console.log("I'm here");
url: "profiles/update_link",
type: "POST",
dataType: "html",
data: {link: link,data: $('#link_hash').val() },
success: function(data) {
// some code
error: function(data1) {
// some code


I have modifies route.rb file to match it to my controllers "update_link" method.
The code in my method is given below:-

def update_link
@tlink=Link.find_by_link(params[:data]) "=========kkkkkkkkkkkkkk=================================#{@link.inspect}" "=========kkkkkkkkkkkkkk=================================#{@tlink.inspect}" "=========kkkkkkkkkkkkkk=================================#{params.inspect}"

respond_to do |format|
if @tlink.nil?
@link.update_attributes(:link => params[:data])

...some code....
...some code...

So in the server log it's showing -

Started POST "/profiles/update_link" for at 2013-02-20 12:08:20 +0530
Processing by ProfilesController#update_link as HTML
Parameters: {"link"=>"9bfzjp", "data"=>"9bfzjpaaa"}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 6ms

So clearly "" is not showing up...Now after searching I was able to solve the WARNING but still 401 is present...How to solve this??

Thanks in advance....

Answer Source

According to your server log, you are not passing CSRF token, so rails automatically considers request to be malicious and flags it as unverified. default handling of unverified requests is to reset session. Can you comment out protect_from_forgery or add skip_before_filter :verify_authenticity_token to your controller to see if it the case?

If you want to include authenticity token in your ajax request (highly recommended) you can add it to headers in your ajax request:

headers: {
      'X-Transaction': 'POST Example',
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download