如何仅当用户单击以确认离开 option.otherwise 查询时才执行查询不应执行

How to Execute query only when user click to cofirm on Leave option.otherwise query should not be execute

这是我的代码

function myfoo(){
    $.ajax({
            type: "POST",
            url: "update.php",
            dataType: 'json',
            data: {
              on_timeout: 1
            },
            success: function (r) {}
       });
    }

     window.onbeforeunload = function(){
          myfoo();
          return 'Are you sure you want to leave?';
     };

我的update.php代码:

session_start(); 
include 'conn.php';

if(isset($_SESSION['Seats'])) {
    $seatS=$_SESSION['Seats']; 
    $Eventid=$_SESSION['Eventid'];
    $cats = explode(" ", $seatS); 
    $cats = preg_split('/,/', $seatS, -1, PREG_SPLIT_NO_EMPTY); 
    foreach($cats as $key => $cat ){ 
        $cat = mysql_real_escape_string($cats[$key]); 
        $cat = trim($cat);
        if($cat !=NULL) { 
            $stmt = $con->prepare('UPDATE fistevent SET Status=" " where Event_Id=? AND seats="'.$cat.'" AND Status="Hold" '); 
            $stmt->bind_param("s", $_SESSION['Eventid']); 
            $stmt->execute(); 
        }
    }
}

尝试以下 beforeunload 绑定:

$(window).on('beforeunload', function () {
   return 'Are you sure you want to leave?';
});
$(window).on('unload', function () {
   console.log('calling ajax');
   myfoo();
});