When a user closes a browser tab, I want to make an ajax request based on what option he clicks.
If he clicks on Leave this page -> Ajax Call 1
If he clicks on Stay on this page -> Ajax Call 2
here is how my code looks like now
I want to do this ajax call after what the user has selected any one of the option. But currently the ajax call runs automatically if the user tries to close the tab
window.onbeforeunload = userConfirmation;
function userConfirmation(){
var cookieName = $.trim("<?php echo $this->uri->segment('5') ?>");
var toValue = $.trim($('#toValue').val());
document.cookie = cookieName+'=; expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/';
var confirmation = 'The message will be discarded.';
$.ajax({
type: 'POST',
url: "<?php echo BASE_URL.'index.php/admin/mail_actions/deleteSessionDatas' ?>",
data: {'toValue':toValue},
dataType: 'html',
success: function(response){
console.log(response);
var response = $.trim(response);
}
});
return confirmation;
}
Well, I put forward that this is a hack and not the solution, this is just a solution.
In order to execute a piece of code (this is suitable not just for AJAX
) only when the user clicks on Stay on this page you have to make it run asychronously, thus javaScript
keeps running synchronous code (the return
statement).
jQuery.ajax()
calls must include the async: true
parameter, then the code to be executed after user's click must be included in a setTimeout()
function with the proper timeout (if the page takes too much time to unload the timeout must be higher)
var stayHere = ""; // this variable helps with the "stay on this page"_code cancellation when user chooses "leave this page"
window.onbeforeunload = userConfirmation;
function userConfirmation() {
var confirmation = "Your edits will be lost";
stayHere = setTimeout(function() { // the timeout will be cleared on "leave this page" click
$.ajax({
url: "ajax-call.php",
type: "post",
data: {chosenOpt: "stay"},
async: true, // important
success: function(data) { console.log(data);},
error: function() { alert("error");}
});
}, 2000); // Here you must put the proper time for your application
return confirmation;
}
How to run code if user clicks on Leave this page
If the user chooses to leave the page, then the page starts to unload and when it has completely unloaded the unload
event fires, so I'll put code in its listener:
jQuery(window).on("unload", function() {
clearTimeout(stayHere); // This is another assurance that the "stay here"_code is not executed
$.ajax({
url: "ajax-call.php",
type: "post",
data: { chosenOpt: "leave"},
async: false, // If set to "true" the code will not be executed
success: function(data) { console.log(data);},
error: function() { console.log("Error");} // In chrome, on unload, an alert will be blocked
});
});
Note: be careful with the code that executes inside an unload
handler. Since the unload
event fires after everything is unloaded, none object in the page is still available.
Here is a jsfiddle to see how does it works.
The ajax-call.php
contains just
echo $_POST["chosenOpt"] . "_" . rand(1, 9999);
And the output will be leave_[number]
on Leave this page and stay_[number]
on Stay on this page
Note: You can see leave_[number]
only refreshing the page and if Preserve Log is checked in console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With