Reputation: 859
I want the function pageleave()
to be called before the user exits a page. But I can't seem to get it to work correctly, I searched the web for a couple hours and can't find a solution. Here is the code I came up with. It runs when the page loads instead of when the page unloads.
window.onbeforeunload = pageleave;
function pageleave() {
$.post("<?php echo dirname( get_bloginfo('stylesheet_url') ); ?>/ajax/videocanle.php", { videoID: "<?php echo $videoID; ?>" },
function(data) {
if ( data != "\nsuccess"){
alert ("Sorry but there was an unexpected error, please try again");
}
});
}
That is the current revision, it still doesn't run the function before the page unloads. The function does work thou, I tested it with a simple input button.
<input type="button" value="test function" onclick="pageleave()" />
Upvotes: 0
Views: 5214
Reputation: 25
Try this:
window.onbeforeunload = function() {
$.post("<?php echo dirname( get_bloginfo('stylesheet_url') ); ?>/ajax/videocanle.php", {
videoID: "<?php echo $videoID; ?>"
});
};
Upvotes: 1
Reputation: 381
You want to pass a reference to the function. In your example you were calling the function in your assignment statement. Try this:
window.onunload = function() {
$.post("<?php echo dirname( get_bloginfo('stylesheet_url') ); ?>/ajax/videocanle.php", {
videoID: "<?php echo $videoID; ?>"
});
};
Upvotes: 2
Reputation: 5894
window.onunload=pageleave;
function pageleave() {
$.post("<?php echo dirname( get_bloginfo('stylesheet_url') ); ?>/ajax/videocanle.php", { videoID: "<?php echo $videoID; ?>" } );
}
Upvotes: 3
Reputation: 225238
You need to assign a reference to the function, not the result of calling the function (which is what the ()
does). Remove the ()
:
window.onunload = pageleave();
(You may also want to use the onbeforeunload
event instead of onunload
, and also return some kind of confirmation message so that your Ajax request has a chance to complete.)
Upvotes: 5