I am using Ruby on Rails v3.0.9 and jQuery v1.6.1. I would like to handle (by using jQuery) a JSON response data when the AJAX HTTP request returns an error (see the code below for more information) in order to display @user.errors messages. That is, …
… in the controller I have:
render :json => @user.errors,
:status => 400
… in the view file I have:
$jQ.ajax({
type: '...',
url: '...',
dataType: 'json',
data: '...',
error: function(jqXHR, textStatus, errorThrown) {
// Here is where I would like to handle the above mentioned `@user.errors`
// array (that is related to the "Ruby on Rails Way" of handling errors).
//
// I tried to use 'alert(jqXHR.base);' but the `@user.errors` array is always
// returned as a string.
alert(...)
},
success: function(data, textStatus, jqXHR) {
...
}
});
There is a way to change the above code so to use something like the following in order to display errors?
# Supposing that'@user.errors' is '{"base":["already exist"]}'
alert(jqXHR.base);
Note: In few words, I would like to handle data as made when I get a success AJAX HTTP request data (function(data, textStatus, jqXHR)‘s permits me to use the JSON parsed data like so: alert(jqXHR.base);).
This is pretty simple. You just need to json-decode the answer returned by the server. Simply use http://api.jquery.com/jQuery.parseJSON/ to do that.