Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redo an AJAX call after failure

I am accessing my website using its REST API service available to me that allows the me to first authenticate and then use that authentication's session returned value to carry out further API calls. I can access it fine and properly without any issues. The session times out after an hour. Lets say I would like to make an API call after an hour, I would like to reauthenticate and continue with an AJAX call that was happening in the first place. Could you suggest me on how I can redo an AJAX call that would first authenticate if the session has timed out and then continue with the original AJAX call that was there in the first place?

$.ajax({
    type: "GET",
    dataType: "json",
    url: "url",
    cache: false,
    async: false,
    success: function (data) {
        alert(data);
    },
    error: function(xhr, textStatus, errorThrown) {
        //$.ajax(this);
        //return;
    },
    statusCode: {
        403: function() {
            var session = retryLogin();
            if(session !== "")
            {
             // call this function again? How can we achieve this?????
            }

        }
    }
});

Kindly let me know how I can call that ajax call again that was supposed to run in the first place?

EDIT: Basically I have two AJAX calls i.e. one for authentication that gets the session ID and the other would be to get some data back based on that session ID. If the session ID expires mid way, I would like to redo the authentication call and then carry on with the AJAX call that was going to happen in the first place. Any suggestions on how I can achieve that?

I have added a diagram of it as well just to show what I would like to achieve.

Scenario

Cheers.

like image 542
Neophile Avatar asked May 12 '15 16:05

Neophile


People also ask

How do you handle Ajax failure?

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function.

How do I return data after Ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

What happens if an Ajax request made using jQuery fails?

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.

What is call back method in Ajax?

The ajaxSuccess( callback ) method attaches a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event.


1 Answers

[I don't understand what "after failure" means to you, but from the following you will understand the line of action and how you can approach your problem]

You can wrap the ajax call in a function and call it again if it's an error.

var callMeAgain = function(){
$.ajax({
    type: "GET",
    dataType: "json",
    url: "url",
    cache: false,
    async: false,
    success: function (data) {
        alert(data);
    },
    error: function(xhr, textStatus, errorThrown) {
       callMeAgain();
       //text statuses for error are: "timeout", "error", "abort", and "parsererror"
    }   
});
};

This is what you're trying to achieve?

The ajax call has a timeout parameter and you can do something like this.

  var callMeAgain = function(){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "url",
        cache: false,
        timeout: 400,
        async: false,
        success: function (data) {
            alert(data);
        },
        error: function(xhr, textStatus, errorThrown) {
            if (textStatus=="timeout") {
                    callMeAgain();
            }
        }   
    });

As i see in a similar answer there must be added that:

Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Let's assume you're writing the exception in some message and we're gonna catch the exception in success function.

 var sessionCallVar = function sessionCall () {
   return $.ajax(...);
};

 var callMeAgain = function(){
        $.ajax({
            ......
            success: function (response) {
                if(response.SessionExceptionMessage !== ''){
                    //then we have a session error
                    sessionCallVar().then(callMeAgain);
                  }
            },
            error: function(xhr, textStatus, errorThrown) {
                .........
            }   
        });

Chaining ajax calls based on promises: How do I chain three asynchronous calls using jQuery promises?

And this is some kind of architecture i embrace in asp.net [i didn't really know about your server-side language] : ASP.NET MVC Ajax Error handling

Ajax error handling and treating custom exceptions in the error callback: jQuery Ajax error handling, show custom exception messages

like image 104
Razvan Dumitru Avatar answered Oct 06 '22 01:10

Razvan Dumitru