Populate field depending on $_POST value

2019-07-10 02:17发布

问题:

I am looking for some help with a form I am trying to populate.

I would usually use an onChange() function, but I don't think that is an option here.

Basically I have a <form> with a couple of hidden values, and a submit button. When submit is hit, it directs to the booking page, where the $_POST values populate a couple of the fields.

<form method="post" action="book.php">
    <input type="hidden" name="title" value="Cardio Fitness">
    <input type="hidden" name="courseID" value="CF">
    <input type="hidden" name="day" value="Wednesday">
    <input type="hidden" name="time" value="9:00pm">
    <input type="submit" Value="Wednesday - 9:00pm">
</form>

The book.php looks like:

<h2><?php echo $_POST['title'];?></h2>

<form id="booking" onSubmit="return check_book()" method="post" action="#">
    <!-- Course Name -->
    <input type="hidden" name="courseID" id="cID" value="<?php echo $_POST['courseID'];?>"/>
    <!-- Course Day -->
    <input type="text" name="day" id="day" value="<?php echo $_POST['day'];?>" readonly/>
    <!-- Course Time -->
    <input type="text" name="time" id="time" value="<?php echo $_POST['time'];?>" readonly/>

    <!-- Adult Spots -->
    <select name="as" class="1-10">
        <option value="" disabled selected>Adult</option>
    </select>
    <input type="text" class="as_price" readonly/>
    <!-- Child Spots -->
    <select name="cs" class="1-10">
        <option value="" disabled selected>Child</option>
    </select>
    <input type="text" class="cs_price" readonly/>

    <!--Submit Button -->
    <input type="submit" value="Add to Cart"/>

</form>

What is the best way to populate the .as_price and .cs_price fields, depending on the $_POST values? JS?

Am I completely off the mark?

Cheers

回答1:

Yes, you would have to use JS if those values change dymanically when changing the other form fields. PHP is a server side scripting language. You could use AJAX to retrieve data from the server if need be.



回答2:

Do you mean (after submitting the form and before loading the other page)?

Then use <?php and take your time doing the calculations using your price logic. (One-time calculation). Example:

<!-- Adult Spots -->
<select name="as" class="1-10">
    <option value="" disabled selected>Adult</option>
</select>
<?php
// Do a db connection if you want to
// Calculate the price using your logic
$final_price = "$".(10*10); // just an example resulting $100
?>
<input type="text" class="as_price" value="<?php echo $final_price;?>" readonly/>

However, after you serve the page to the client, forget about PHP, it isn't an option to change anything. Use AJAX to send requests to a price-checking-file.php on selection change, and update the price accordingly.