3

In an ajax success function, is it assumed the status code is 200? or could it be successful if you return 304 or 503?

What actually defines it's successful?

fosho
  • 127
  • 8
  • Importantly, a server-sent 304 will only render in JavaScript as a 304 if you include caching information in your request. Otherwise, the browser will tell JS it was 200. (see https://stackoverflow.com/q/5173656/710446) I'm not sure if a JS-visible 304 caused by sending caching information will be treated as a "success" by jQuery, though. – apsillers Oct 21 '19 at 17:11
  • To answer your original question: Yes, "success" generally implies an HTTP 200. But, per my reply below, a lot of different things besides a non-HTTP 200 can trigger a "fail". You can even have an HTTP 200 and still "fail", One of your examples, HTTP 304, is a "special case". Look [here](https://www.telerik.com/blogs/understanding-http-304-responses) or [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304). Q: Is your question answered? – paulsm4 Oct 21 '19 at 17:40

1 Answers1

2

You're correct, jQuery ajax will "fail" if it receives an HTTP 503 ... or 500, or 404, etc. It will also (obviously) fail on ECONNREFUSED or any socket-level (communications) error.

Here is the documentation:

https://api.jquery.com/jquery.ajax/

jQuery.ajax(): Perform an asynchronous HTTP (Ajax) request.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

https://api.jquery.com/deferred.fail/

deferred.fail(): Add handlers to be called when the Deferred object is rejected.

It's worth noting that the connection can succeed ... the server can return HTTP 200/OK ... and your jQuery Ajax call can STILL trigger a "fail".

For example, if you're expecting a JSON response, and the server returns XML:

https://www.mkyong.com/jquery/jquery-ajax-request-return-200-ok-but-error-event-is-fired/

ADDITIONAL INFO:

  • To answer your original question: Yes, "success" generally implies an HTTP 200.

  • But a lot of different things besides a non-HTTP 200 can trigger a "fail".

  • You can even have an HTTP 200 and still "fail" (per the link above).

  • Or have a non-HTTP 200 and still "succeed" (for example, HTTP 201).

  • HTTP 304, is a "special case". Look here or here.

Q: Is your question answered?

paulsm4
  • 114,292
  • 17
  • 138
  • 190