How to Execute Ajax Function Onbeforeunload

How to execute ajax function onbeforeunload?

You fire your ajax async (default for jquery - ajax). But the browser won't wait for anything on unload.

try setting async : false in the ajax-settings. But you can never be sure that this will work in all browsers everytime.

see the comment here:
http://api.jquery.com/unload/#dsq-comment-body-132164390

window.onbeforeunload ajax request in Chrome

I was having the same problem, where Chrome was not sending the AJAX request to the server in the window.unload event.

I was only able to get it to work if the request was synchronous. I was able to do this with Jquery and setting the async property to false:

$(window).unload(function () {
$.ajax({
type: 'GET',
async: false,
url: 'SomeUrl.com?id=123'
});
});

The above code is working for me in IE9, Chrome 19.0.1084.52 m, and Firefox 12.

How to perform an ajax call on page unload?

No. During unload, the browser will kill all pending requests. So the AJAX might or might not arrive at the server. You also can't do it inside the handler of the beforeunload event because the first A in AJAX means: Asynchronous -> Just put the request on the stack and eventually execute it. So the request will be looked at only after the handler returns. But very soon after that, the browser will kill anything related to the page.

The solution is to always send updates to the server while the users makes changes. Put those into a special "temporary" table from which you can restore the state later.

You could also use something like localStorage in the browser but then, the data wouldn't move with the user. For example if they were working on an tablet and that broke or had a power loss, they could move to their PC to continue where they left off.

Cannot enstablish ajax connection onbeforeunload event

You have to use async: false in AJAX requests sent onbeforeunload, otherwise the tab is destroyed before the response can be handled. Try this:

$(window).on("beforeunload", function() {
$.ajax({
url: "unload.php?name=SOME_VARIABLE",
type: "POST",
async: false,
success: function(data) {
// your code here...
}
});
});

Note that this is the only situation in which synchronous AJAX requests should ever be used. In all other cases they should be sent asynchronously.



Related Topics



Leave a reply



Submit