Javascript -Way to determine which parameter the user clicks on the navigation popup

When the user closes the browser tab, I want to make an ajax request based on which option he clicks.

If he clicks the button "Leave this page" β†’ Ajax Call 1

If he clicks the button β€œStay on this page” β†’ Ajax Call 2

this is what my code looks like now

I want to make this ajax call after the user has selected any of these options. But currently, ajax call is done 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;
}
+4
source share
1 answer

Well, I said this is a decision, not , a .

( AJAX), Stay on this page, , javaScript ( return).

jQuery.ajax() async: true, , , setTimeout() ( , )

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;
}

, Leave this page

, , unload, :

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
});

});

. , unload. unload , , .

jsfiddle, , .

ajax-call.php

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

leave_[number] Leave this page stay_[number] Stay on this page

. leave_[number] , .

+3

All Articles