Ajax query when user closes the window?
I want to execute an ajax query when one user close the window. Ive got this code:
var $jQ = jQuery.noConflict();
$jQ(window).bind('unload', function() {
$jQ.ajax({
type: "GET",
url: "http://www.mydomain.com/post_untrack.php" ,
success: function(msg){
alert("Untrack");
}
});
});
I receive the "alert" event, but the script is not开发者_开发技巧 executed...
post_untrack.php:
<?php
mail("myemail@mydomain.com", "Script executed", "Hooray!!!");
?>
Any idea ?
Thanks!!!
To make this work, you need to add the property
async: false
to .ajax()
options object, plus you need to execute it on onbeforeunload
so in jQuery
$jQ(window).bind('beforeunload',...);
By default, ajax requests are asynchronous. So although you may start the request when the window is unloaded, it will probably get cancelled immediately and never actually sent to the user. Although you could make the request synchronous, synchronous requests really mess up the user experience by bringing the browser to a screeching halt.
More about this in this other SO question and its answers.
And of course, any ajax calls will be subject to the Same Origin Policy, if that's relevant.
is the URL being posted to on the same domain as the page that is trying to do the ajax call?
http://en.wikipedia.org/wiki/Same_origin_policy
精彩评论