Siddharth Siddharth - 6 months ago 21
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:

$(document).ready(function(){
var link=$('#link_hash').val();
$("#update_link").click(function(){
console.log("I'm here");
$.ajax({
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
@link=Link.find_by_link(params[:link])
@tlink=Link.find_by_link(params[:data])
logger.info "=========kkkkkkkkkkkkkk=================================#{@link.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{@tlink.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{params.inspect}"

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

...some code....
else
...some code...
end
end
end
end


So in the server log it's showing -

Started POST "/profiles/update_link" for 127.0.0.1 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 "logger.info" 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

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')
}
Comments