Rest – Can REST, Ajax and jQuery work well together

ajaxjqueryrest

I'm trying to use REST (usign spring MVC) as my Ajax backend but got some problems when using it with jQuery. REST best pratices recommend using HTTP status code, e.g. 200, 403, 401, etc, and I have no problem with a 200 status code, jQuery's ajax method have a done(data) callback that let me read the reponse in json format. But when I need to return some error in json format along with the status code, I got stucked. The fail(jqXHR, textStatus) callback doesn't seem to support json in the response. So if I return JSON from the serverside, it will be put in jqXHR.reponseText and treated as plaintext instead.

So my question is, is REST good for Ajax? Why does jQuery treat the data differently in case of non-200 status code?

Best Answer

It is very common to use REST in combination with Ajax.

This has not really much to do with REST or any other architecture. Using the correct HTTP status code in case of errors should be the recommendation in any case (there may be exceptions I am not aware of, though).

I don't know why the jQuery team decided to handle it this way, but they may have simply decided that in case of success the resturned value is well defined while in case of error it may be anything (a simple text message being one choice).

In any case you can parse the message manually if you decide to return JSON like this:

var msg = $.parseJSON(err).msg;