Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle jQuery ajax post error when navigating away from a page

Tags:

jquery

ajax

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.

like image 690
Steve Walsh Avatar asked Feb 10 '12 14:02

Steve Walsh


People also ask

What is the correct approach to handle Ajax error when Ajax request fails?

To handle jQuery AJAX error. The ajaxError( callback ) method attaches a function to be executed whenever an AJAX request fails.

Is there any way to wait for Ajax response and halt execution?

Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.

Does Ajax follow redirect?

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.


1 Answers

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:

  1. If the state is UNSENT or OPENED, return 0 and terminate these steps.

  2. If the error flag is set, return 0 and terminate these steps.

  3. 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

like image 166
Steve Walsh Avatar answered Oct 07 '22 01:10

Steve Walsh