I have this kind of javascript:
$.ajax({ url: "//myapi.com/json", dataType: "jsonp" }).done(function (data) { selectText('Id', data.country); }).fail(function (jqXHR, textStatus, errorThrown) { var defaultOption = 'US' selectDropdownByText('Id', defaultOption); console.log(errorThrown); });
But the thing is that on https request my ajax is not working because service I am calling is not accessible via https and I am getting error :ERR_CONNECTION_REFUSED
- so that is fine, I just want to handle that. I have .fail
in ajax call, but it is not handling :ERR_CONNECTION_REFUSED
Could you give advice on how to handle :ERR_CONNECTION_REFUSED
in that case?
I also was trying to wrap my ajax call to try-catch
block, but it wasn't working either.
Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests. The fail() callback takes 3 parameters where the first parameter is a JSON error object, the second parameter is given a reason in text format and the last parameter is for the error thrown by the HTTP request.
The ajaxError() method specifies a function to be run when an AJAX request fails. Note: As of jQuery version 1.8, this method should only be attached to document.
404 - Not Found. The URL requested was not found on the server. Check for typos in the file name in the ajax parameter and in your file on the server.
You can use timeout
property of $.ajax
to fire the error
callback.
This will make sure that the error
callback is fired if the server doesn't respond within a particular time limit.
$.ajax({ url: "//myapi.com/json", dataType: "jsonp", timeout: 15000 // adjust the limit. currently its 15 seconds }).done(function (data) { selectText('Id', data.country); }).fail(function (jqXHR, textStatus, errorThrown) { var defaultOption = 'US' selectDropdownByText('Id', defaultOption); console.log(errorThrown); });
This will trigger the fail
callback when there is no internet as well.
It appears that when jqXHR.readyState (i.e., the readyState field of the first parameter to the $.ajax(...).fail() method) is 0 that a network error has occurred. However, I have not been able to ascertain what the exact network error is via JavaScript.
I have looked at the jQuery Ajax code, and xhr.send() (i.e., the XMLHttpRequest.send()) method (which generates the network error) does not catch nor throw the error. Thus, it is not possible to catch it.
It appears that the browser detects and displays the correct error message but that jQuery is oblivious to the specific type of network error that occurs.
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