I need some suggestions here or maybe some explanations. I have a jquery ajax call,
$.ajax({ type: "GET", url: base_url+'/ajax/fetch/counts/', dataType: 'json', data: {}, error: function(xhr, error){ console.debug(xhr); console.debug(error); }, success: display_counts });
It's working fine. My success
callback fires correctly with response. But, what I noticed is that my error
callback is fired every time, even when my call returns success status 200. In the above error
callback, I see that object xhr.status
is 200.
Can anybody explain what's wrong, or what is happening here? error
callback is supposed to fire only when I have 404 or maybe a non-200 response. Are my assumptions correct?
Thanks.
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. Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.
The function specified by the ajaxError() function is called when the request fails or generates the errors. We can use the fail() callback function as well on the JavaScript promise object( the jqXHR object return by the $. ajax() function) to run the specific function on the ajax request fail.
What About jQuery and AJAX? jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Just an suggestion, try using the $.ajaxSetup() to get the correct error like this:
$(function() { $.ajaxSetup({ error: function(jqXHR, exception) { if (jqXHR.status === 0) { alert('Not connect.\n Verify Network.'); } else if (jqXHR.status == 404) { alert('Requested page not found. [404]'); } else if (jqXHR.status == 500) { alert('Internal Server Error [500].'); } else if (exception === 'parsererror') { alert('Requested JSON parse failed.'); } else if (exception === 'timeout') { alert('Time out error.'); } else if (exception === 'abort') { alert('Ajax request aborted.'); } else { alert('Uncaught Error.\n' + jqXHR.responseText); } } }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With