Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery consider an 200 response Ajax request with empty content as fail()?

Tags:

jquery

First, there's no cross-region problem at all.

I found if the server response an empty content body, jQuery consider this as fail()?

Why is this?

like image 256
mko Avatar asked Oct 14 '13 03:10

mko


People also ask

What happens if an Ajax request made using jQuery fails?

version added: 1.0. Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time.

How do I know if Ajax request is successful?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

How many arguments does our Ajax function call require?

The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. The type of data that you're expecting back from the server.

How can Ajax call error be resolved?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.


2 Answers

If you're using jQuery >= 1.9 an empty JSON response will be rejected, according to the API documentation:

The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.

like image 90
WynandB Avatar answered Oct 09 '22 04:10

WynandB


WynandB is correct, however there is an alternate resolution: have the server return HTTP 204 No Content instead, which will make jQuery ignore the parsing error.

like image 35
pimlottc Avatar answered Oct 09 '22 05:10

pimlottc