Anupam
Anupam

Reputation: 8016

onbeforeunload wait for ajax result

Is it possible for onbeforeunload() function to wait for ajax result and move to a jsp based on the resultvalue or atleast show a message before unloading?

IS it possible to use setTimeOut or some custom wait function for this problem or i have to think of some other workflow

Upvotes: 1

Views: 5256

Answers (4)

user1079877
user1079877

Reputation: 9368

This is my strategy and works for me:

_number_of_active_ajax ++;
$.ajax({
    url: REQUEST_URL,
    timeout: 3000
})
.always(function() {
    _number_of_active_ajax --;
});

window.onbeforeunload = function() {
    if(_number_of_active_debounce > 0 || _number_of_active_ajax > 0)
        return "Your question";
}

}

It will show a message to use if the page has an active request.

Upvotes: 0

Haresh Vidja
Haresh Vidja

Reputation: 8496

It is not good Idea to display alert box for waiting response from ajax. Generally you can use alert box for message for confirmation of Leaving page after ajax response.

For avoiding use of alert you can call Ajax synchronously for example

if(window.XMLHttpRequest) xmlHttpObj=new XMLHttpRequest();
else xmlHttpObj=new ActiveXObject("Microsoft.XMLHTTP");
if(xmlHttpObj){
xmlHttpObj.onreadystatechange=function(){
if(xmlHttpObj.readyState==4 && xmlHttpObj.status == 200){
 // your logic required
}
}
xmlHttpObj.open("GET", "your request url", false); // used false for synchronous call 
xmlHttpObj.send(null);
}
else{
alert("AJAX not support");
}    

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Use a synchronous XmlHttpRequest call ("AJAX" is a mis-nomer).

Upvotes: 3

Mike
Mike

Reputation: 2587

AFAIK, it is not possible. onbeforeunload has very limited functionality, otherwise malicious sites could stop you from leaving their site.

Addendum: It is possible to show a message like 'You are leaving this page'. In that case, the beforeunload() function must return a string.

Example

window.onbeforeunload = function() {
   return 'Are you sure about that?';
}

Upvotes: 0

Related Questions