php - Javascript -Way to detect on what option user clicks on Navigation Popup


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.';
    type: 'POST',
    url: "<?php echo BASE_URL.'index.php/admin/mail_actions/deleteSessionDatas' ?>",
    data: {'toValue':toValue},
    dataType: 'html',
    success: function(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 forAJAX) only when the user clicks on Stay on this page you have to make it run asychronously, thusjavaScript keeps running synchronous code (thereturn statement).

jQuery.ajax() calls must include theasync: true parameter, then the code to be executed after user's click must be included in asetTimeout() 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
            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 theunload 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
    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 anunload handler. Since theunload event fires after everything is unloaded, none object in the page is still available.

Here is a to see how does it works.

Theajax-call.php contains just

echo $_POST["chosenOpt"] . "_" . rand(1, 9999);

And the output will beleave_[number] on Leave this page andstay_[number] on Stay on this page

Note: You can seeleave_[number] only refreshing the page and if Preserve Log is checked in console.

People are also looking for solutions to the problem: javascript - How to force jquery's trigger function to trigger all events in forloop?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.