The $ .ajax call throws an error when viewing to another page before the request is completed

I ran into an issue in Firefox (not happening in IE) where my Javascript is triggering a service call, which might take a little time to load. If the user navigates to another page before the call completes, the error

object's method is called jQuery.ajax()

.

I am also looking for a way:

  • No error is thrown when the user views another page when the request doesn't end, OR
  • The error method distinguishes between β€œreal” errors and this error.

My error method, unsurprisingly, shows the user an error, and I don't want to do this when the error is caused by moving to another page.

My simple test code includes the following Javascript and a service that sleeps for 20 seconds and then returns a string.

<script type="text/javascript" language="javascript">
    $(document).ready(function ()
    {
        $('#testLink').click(function ()
        {
            $.ajax({
                type: "POST",
                url: "/Services/NU.Web.NUnet.Services.UserService.asmx/LongRunningService",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, xhr)
                {
                    console.log(data);
                    console.log(textStatus);
                    console.log(xhr);
                },
                error: function (xhr, textStatus, errorThrown)
                {
                    console.log(xhr);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        });
    });
</script> 

      

+2


a source to share


1 answer


Try:



<script type="text/javascript" language="javascript">
    $(function() {
        $('#testLink').click(function() {
            $.ajax({
                type: "POST",
                url: "/Services/NU.Web.NUnet.Services.UserService.asmx/LongRunningService",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, xhr){
                    console.log(data);
                    console.log(textStatus);
                    console.log(xhr);
                },
                error: function (xhr, textStatus, errorThrown) {
                    if (xhr.status === 500) {
                        console.log(xhr);
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                }
            });
        });
    });
</script> 

      

+3


a source







All Articles