jQuery ajax success and error method args reversed, why?
My jQuery fu is new, so forgive the obvious if this question is indeed that.
jQuery ajax documentation shows error and success defined as follows:
error(jqXHR, textStatus, errorThrown) success(data, textStatus, jqXHR)
This is hosing me a bit consistency-wise as, by default, server-side I return status (200, 401, 404, etc.) along with a JSON encoded response, which could be a json error or success string, array, object and so on.
Basically what is happening is that on success receiving json string (coffeescript)
success: (data) -> $('#status').html( data )
I can print the json response string directly, which is confusing, as the equivalent error version requires me to parse the json string and access the responseText attrib of the data object:
error: (data) -> $('#status').html( jParse(data.responseText) )
So, how can I get client-side to mirror server-side consistency? i.e. respond with json server-side and know that I need parse/access object attrib(s) on client.
As I understand it, in "RESTful" services where success (or otherwise) is indicated in the HTTP status code, you're not supposed to put meaningful content in the HTTP body of an error condition. Put it in the text of the 40x error code instead.
Ok, a bit clearer now:
ajax success's first argument, data, is automatically parsed according to mime type if no dataType param option was set.
That explains why, when handling a json map containing say, an order number, I do not have to parse it client-side, could simply refer to data.orderNum
On the other hand, there is no such mime type inference on ajax error's first argument, jqXHR, which explains why I do have to parse the reply prior to referencing attribs like data.responseText.
Probably old hat to many, but good to know what to expect from success/error, was getting double, double quoted string replies and other oddities...