Trouble on handling jQuery.ajax responses in a controller
I am using Ruby on Rails 3.0.7 and jQuery 1.6.1. I am trying to implement an AJAX request using the jQuery $.ajax()
syntax and I have a problem on the response for which is triggered always the error callback.
N.B.: router is successfully set.
In the controller I have:
def test_method
...
respond_to do |format|
format.js
end
end
The jQuery AJAX code for the request is:
$('#test_html_css_id').bind('click', function() {
$.ajax({
type: "POST",
url: "<%= user_url(@user)%>/test_method",
data: "test_data=<%= @user.test_data.to_s %>",
dataType: 'js',
error: function(jqXHR){
alert( "ERROR " + jqXHR );
},
success: function(jqXHR){
alert( "SUCCESS " + jqXHR );
}
});
});
In the above example on the click
event it returns always the following alert me开发者_开发问答ssage:
ERROR [object Object]
How can I return explicitly a success or error response in my controller?
BTW: How can I return some data from the controller and then handle that with in a trigger in the jQuery code?
UPDATED after the @dgvid comment
Using in the jQuery code this
error: function(xhr, status, ex) {
var msg = "";
if (xhr) {
msg = "readyState is " + xhr.readyState + ". ";
}
if (ex) {
msg += ex.name + ' - ' + ex.message;
}
alert("ERROR " + msg); },
I get the following alert message:
ERROR readyState is 4. SyntaxError - invalid label
What means that?
How can I return explicitly a success or error response in my controller?
You can do this by using the HTTP status codes, 200 is success and 500 is a server error. So try using some code like:
if @object
respond_to do |format|
format.js
end
else
render :nothing => true, :status => 500
end
The SyntaxError exception with message "invalid label" probably indicates that the $.ajax method is trying to parse the response data as either JavaScript or JSON, but then encountering something in the response that is not syntactically valid for that type. Try changing the dataType field in your call to "text", just temporarily. See if that gets you beyond this error and allows you to see what you actually getting back from the server.
By the way:
- The docs for jQuery.ajax do not list "js" as a valid argument for dataType. You probably want "script" or maybe "json" or "jsonp," instead.
- If dataType not is not set, and I suspect if it is not valid, then $.ajax tries to infer the type from the response's MIME type.
Edit: I should have also mentioned -- if you are running with Firebug or something equivalent, try using the Net tab to examine the server response. Given the MIME type of the response, is it syntactically valid? If not, you either need to correct the response coming from the server, correct the MIME type set on the response, or change the dataType in the $.ajax call.
精彩评论