Search code examples
phpajaxonbeforeunload

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


That is my code

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

my update.php code:

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

Solution

  • Try below beforeunload binding:

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