Redo an AJAX call after failure
Asked Answered
P

2

15

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.

Pirog answered 12/5, 2015 at 16:2 Comment(4)
Since retryLogin has to perform an AJAX call, it will be asynchronous. You need to pass a callback to it, and the callback will call this function again.Adalai
Maybe you can wrap the main ajax call inside a function and recall it inside the error handle if the error code is the one of the invalid session, basicaly a recursionVaricella
Could you possibly post that as an answer please with more detail so that I can try it out?Pirog
Possible duplicate of How do I resend a failed ajax request?Brigandine
C
11

[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

Chaschase answered 9/6, 2015 at 16:5 Comment(13)
This is not really what I'm looking for. 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?Pirog
What carry on means to you? Create an ajax call (ajax1) which will check your session. If you don't find any session ID then you should make another ajax call (ajax2) which will return a session ID to you and into success function of ajax2 you can place another ajax call (ajax3) which is "going to happen in 1st place". If you find a session ID then you should only call ajax3. This is what you're trying to do?Chaschase
Yes that's correct but look at it from the opposite process. I already have a session that has expired and I am in the middle of the app, where I am making ajax call 3 and I do not have a valid session. I would like to make ajax call 1 again and then ajax call 3 again.Pirog
Wrap your server calls in a method that check the session object, return an exception code which you can identify and create a $.ajax wrapper which is checking if you receive that exception code. And if you receive that exception code make call to return a new session ID and continue call. I think this is what you want to achieve, but is very out of topicChaschase
Yes this is what I would like to achieve. Could you possibly post that as the answer please?Pirog
To post what? All this mechanism require a lot of code. And i really didn't know what is your server technologyChaschase
Both calls are AJAX calls like the one above. Can I not just perform an AJAX call for session ID (call 1) on the failed event of call 3 and then use that new session ID for a recall of AJAX call 3? Just thinking on how I can achieve it.Pirog
Of course you can do that. callMeAgain is your 3rd AJAX call and in the error function or in the succes function of callMeAgain (depends how you implement your wrappers/what error did you want to catch) you must declare a var firstCall = function first() {return $.ajax(...);} and then call firstCall().then(callMeAgain) and this is itChaschase
I've updated my answer [i think it's accordingly with what you want]Chaschase
your answer looks fine to me, however the callmeAgain function will not go to the success function I think. It will get to the error bit, in which case do we have to place that code in the error function?Pirog
If the server-side is implemented as it is described in the asp.net link, the call will end in success function. Ajax error function is just for timeout, abort and so on. It depends what status you set on server-side. I've updated my answer with another perspective using the error function.Chaschase
Is there anything else that you want me to clarify?Chaschase
I'm actually trying it out myself using your approach. I'll get back to you and accept the answer once I'm completely satisfied. Thanks for your answer. I'll post back if I have any questions.Pirog
C
0

if you for some reason, lost the connection for long-long time, always lost your session info, I recommend use the answer suggested by @RazvanDumitru but if you (lost your internet connection any way) and you want to recuperate all your session info, you need make some storage in database (package all your vars in some like json-string) and generate some key to identify, and when you recuperate your session and logging new again, read all vars from db.

use https://plugins.jquery.com/cookie/ to store keyvalue to identify your vars in browser cookie.

Note: if you want more security(obviously need generate key in some random form) and if you like, protect them with some public key. and then store in browser. you can do all of that with javascript codes or server scripts.

Cabbala answered 15/6, 2015 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.