Is there a way to handle the error from an ajax request within JQuery such that when the user navigates away from the page, the resulting error is ignored?
$(document).ready(function() { $.ajax( { url:'/server/url/', type: 'POST', data: {some..data}, success:function(response) { do stuff with response }, error: function(xhr, textStatus, errorThrown) { // Don't raise this alert if user has navigated away from the page alert('error'); } });
I'm curious if anybody knows of a clean way to handle this? I know you could create some logic in a $(window).bind("beforeunload", function(){})
method but I'd prefer if there was a way to handle the situation without doing this since Chrome appears to no longer support it. Is there for example a specific error that is returned in this case?
Thanks.
To handle jQuery AJAX error. The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails.
Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.
ajax appears to always follow redirects. How can I prevent this, and see the redirect without following it? There are various questions with titles like "jquery ajax redirect" but they all appear to involve accomplishing some other goal, rather than just directly checking the status that a server gives.
It looks like the answer to this is to examine the jqXHR.status. The XMLHttpRequest spec outlines these steps to set the status:
The status attribute must return the result of running these steps:
If the state is UNSENT or OPENED, return 0 and terminate these steps.
If the error flag is set, return 0 and terminate these steps.
Return the HTTP status code.1
NOTE also: The error flag indicates some type of network error or request abortion. It is initially unset and is used during the DONE state.
From what I understand therefore, this code check should fix the issue:
if (xhr.status == 0) alert('error');
1https://web.archive.org/web/20120204040047/http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute
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