2

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

?>

1 Answer 1

2

Solution:

...
// Move the `onClick` function all to `onsubmit` in the form tag. 
<form onsubmit="displayCheck();" action="ss.php" method="post">
...
var b = <?php echo $b; ?> + total ;
document.getElementsByName("value")[0].value = b; //<-- Notice the selection of first array
window.alert(b);   // Will display the total value of selected seats.

}
...

How and Why?: When you are executing the page ss.php , you are setting the value of $b as 0, so until the value is changed inside php for that execution, the value will remain the same.

So when the above page renders, the values of $b are echoed as below.

...
 <input type="hidden" name="value" value="0">
...
 var b = 0 + total ;
...

Now this is where the job of php ie. [Backend] is done and is handed over to javaScript (js) ie. [Frontend].

Now on frontend when you do your calculation, the value of the <input> is still 0. Where as the value of the variable b has been updated. So in order to pass that new value of b with the form, you will have to update the value of the <input>.

Hence the "Solution"..

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

I tried to do as you suggested but same results, I have updated above codes please can you check where i am wrong @9KSoft
Most probably, your form is being posted even before you could update the value of the field named value. You will have to prevent the automatic posting of that form and do it manually OR try looking into using Ajax to post your form. M on mobile right now, so maybe will update when back on my work station.
Let me try manually, if you will update when you are on your work station will be appreciated.
Ok, it was my bad, had overlooked that the selector document.getElementsByName returns an array and we have to select the first element. Alternatively you could use getElementById and give your input an id its a lot easier that way, and lesser margin for errors. Also I'd recommend that once you are comfortable with js, you look into jQuery, it will make your work a lot easier.
Oooh i got the point now, Thanks much again let me work on it @9KSoft

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.