In the below codes what I am trying to do is send the total value amount of ticket then from Javascript to PHP the action_page.php is the receiver but the problem is every time the Reserve Button is clicked it sends 0 while at the same time when a user chooses a seat and if I use window.alert(b); to display the currently selected value it shows without any problem. The problem only appears when using the button to send the values to PHP from Javascript.
Where am I wrong? Below are the codes
ss.php //main page
<!DOCTYPE html>
<html lang="en">
<head>
<title>Seat(s)</title>
</head>
<body>
<?php
$b=0;
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['submit'])) { //Seat Reserve
require 'action_page.php';
}
elseif (isset($_POST[''])) { //Cancel
require 'mypage.php';
}
}
?>
<h2>Please choose a seat to book</h2>
<form action="ss.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<span id="selected-seats"></span> <!-- container for selected seats -->
<br>
Total: <span id="total-container"></span> USD
<button type="submit" class="btn btn-primary" name="submit" onClick="displayCheck()">Reserve Now</button>
<input type="hidden" name="value" value="0">
</p>
</form>
<script>
const selections = {};
const inputElems = document.getElementsByTagName("input");
const totalElem = document.getElementById("total-container");
const seatsElem = document.getElementById("selected-seats");
for (let i = 0; i < inputElems.length; i++) {
if (inputElems[i].type === "checkbox") {
inputElems[i].addEventListener("click", displayCheck);
}
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
id: e.target.id,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
const result = [];
let total = 0;
for (const key in selections) {
result.push(selections[key].id);
total += parseInt(selections[key].value);
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join(",");
//window.alert(result); //Hold Number of Seats Selected.
//window.alert(total); //Hold Total Cost of Selected Seats.
var b = <?php echo $b; ?> + total ;
document.getElementsByName("value").value = b;
window.alert(b); //Hold Number of Seats Selected.
}
</script>
</body>
</html>
action_page.php //For receiving value from ss.php
<html>
<head>
<title>Seats Feedback</title>
</head>
<body>
<?php
echo "<br>";
$myval = $_POST['value'];
print_r($myval);
?>