Here is my code
function myfoo() {
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
async: false,
data: {
Eventid: 1,
Seats: 'Seats'
},
success: function(r) {}
});
}
$(window).on('beforeunload', function() {
return 'Are you sure you want to leave?';
});
$(window).on('unload', function() {
console.log('calling ajax');
myfoo();
});
update.php code
<?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();
session_destroy();
}
}
}
?>
The AJAX data:
parameters are put in $_POST
, not $_SESSION
.
You can't use mysql_real_escape_string
if you're using mysqli
. You don't need to escape parameters when you're using bind_param()
. And you can use explode()
instead of preg_split()
, since there's no regular expression pattern in your delimiter; array_filter()
can be used to remove blank entries.
<?php
include 'conn.php';
if(isset($_POST['Seats'])) {
$seatS=$_POST['Seats'];
$_SESSION['Seats'] = $seatS;
$Eventid=$_POST['Eventid'];
$_SESSION['Eventid'] = $Eventid;
$cats = array_filter(array_map('trim', explode(',', $seatS)));
$stmt = $con->prepare('UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`= ? AND `Status`="Hold" ') or die($con->error);
$stmt->bind_param("ss", $_POST['Eventid'], $cat);
foreach($cats as $key => $cat ) {
$stmt->execute();
}
}
?>