-2

I have these below codes which give user option to reserve a seat according to their choice. These 3 mentioned below are difficulties that I am facing I need help.

  1. To send the total value of a variable named total from Javascript to PHP
  2. To send the total number of selected seats which are being hold by a variable called results from Javascript to PHP
  3. How to make a Reserve Now button inactive if a user did not select any seat from checkbox.

These below are my codes.

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Seat(s)</title>
  </head>
  <body>

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    if (isset($_POST['submit'])) { //Seat Reserve

        require 'action_page.php';

    }

     elseif (isset($_POST[''])) { //Cancel

        require 'mypage.php';

    }
}

//
$parameter = "this is a php variable";
echo "var myval = foo(" . parameter . ");";
?>



?>

    <h2>Please choose a seat to book</h2>
    <form action="index.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">Reserve Now</button>
      </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 myval = foo("this is a php variable");  // I tried to take this value and output it but it didn't work out.

 $.ajax({
  type: 'POST',
  url: 'action_page.php',
  data: {'variable': total},
});
    </script>





  </body>
</html>

action_page.php

<html>
<head>
<title>Seats Feedback</title>
</head>

<body>


<?php

echo "<br>";

$myval = $_POST['variable'];

print_r($myval);  

?>

Looking forward to hear from you guys.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Wilson
  • 117
  • 1
  • 2
  • 10
  • @ggorlen Kindly check new question. – Wilson Jul 21 '18 at 10:55
  • check [this answer](https://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Braca Jul 21 '18 at 11:07
  • Use Javascript to activate and deactivate the submit button. Then use hidden inputs in your form to convey the values you computed ( `total` & `results`) with Javascript. – KIKO Software Jul 21 '18 at 11:08
  • @KIKO Software How can you give an example on using hidden inputs? – Wilson Jul 21 '18 at 11:52
  • See: http://jsfiddle.net/CN8XL – KIKO Software Jul 21 '18 at 13:10
  • There is an important design decision you should edit your question to resolve: do you want your page to refresh and redirect you to another page, or do you want to send the data to the server and get a response using AJAX without a page refresh? – ggorlen Jul 21 '18 at 18:53
  • I want it to refresh and redirect to another page. @ggorlen – Wilson Jul 22 '18 at 22:06

1 Answers1

1

When you're not doing AJAX, posting data to a PHP script the old fashioned way is a matter of:

  1. setting the action attribute on a <form> element to point to the destination PHP script URL
  2. ensuring your form's <input> elements contain all of the data you want to post
  3. adding a submit button to the form

For step 1, currently, your form says to send the post request to itself. This is totally fine (you can use a <?php block ?> like you're doing to determine whether to show a success confirmation or a blank form depending on the contents of $_POST, but I'm guessing your intention is to ultimately send the data over to action_page.php. I made that the action target and removed all of the PHP from your index.

As for step 2, your total isn't currently in an <input> element and won't be posted. I created an invisible total element for this purpose: <input type="hidden" name="total" id="hidden-total" value="0"> and added a couple lines to the script to retrieve this element and set its value whenever your total is recalculated. You could combine the two total elements and style one to look and be non-editable (exercise for the reader).

Another problem relating to step 2 is that you have four different elements with the name vehicle. Only one of these name/value pairs will be posted, so I updated these elements to use unique names so they'll all be sent.

Step 3, making sure you have a submit button, you've already done successfully.

To verify it's working, you can var_dump($_POST) on the receiving PHP script to see the results of the post request or retrieve a specific value by name with e.g. $_POST['total']. At this point, your PHP script can go ahead and parse/validate/sanitize the post data, render proper response output, do a redirect, and/or do whatever else needs to be done, such as writing to a database.

Here's the full code:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Seat(s)</title>
  </head>
  <body>
    <h2>Please choose a seat to book</h2>
    <form action="action_page.php" method="post">
      <input type="checkbox" name="vehicle-a1" id="A1" value="100">$100<br>
      <input type="checkbox" name="vehicle-a2" id="A2" value="65"> $65<br>
      <input type="checkbox" name="vehicle-a3" id="A3" value="55"> $55<br>
      <input type="checkbox" name="vehicle-a4" id="A4" value="50"> $50<br>
      <input type="hidden" name="total" id="hidden-total" value="0">

      <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">Reserve Now</button>
      </p>
    </form>

    <script>

      const selections = {};
      const inputElems = document.getElementsByTagName("input");
      const totalElem = document.getElementById("total-container");
      const hiddenTotalElem = document.getElementById("hidden-total");
      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;
          hiddenTotalElem.value = total;
          seatsElem.innerHTML = result.join(",");
      }

    </script>
  </body>
</html>

action_page.php

<!DCOTYPE html>
<html lang="en">
  <head>
    <title>Seats Feedback</title>
  </head>
  <body>

    <?php

      echo "<pre style='font-size: 1.5em;'>"; // format debug post dump

      var_dump($_POST);

    ?>

  </body>
</html>

Sample output

array(5) {
  ["vehicle-a1"]=>
  string(3) "100"
  ["vehicle-a3"]=>
  string(2) "55"
  ["vehicle-a4"]=>
  string(2) "50"
  ["total"]=>
  string(3) "205"
  ["submit"]=>
  string(0) ""
}

As before, this isn't an industrial strength example and there is plenty of room for improvement, but hopefully it does communicate the basic idea.

ggorlen
  • 44,755
  • 7
  • 76
  • 106