校园预约系统:实现日期表单无跳转执行PHP代码并计算天数
Got it, let's fix that page refresh issue while calculating your reservation days. Here's a step-by-step solution using modern JavaScript (Fetch API) and adjusted PHP code to achieve a seamless, no-refresh experience:
1. Update Your HTML Form
First, tweak the form to remove the default action/method, add a container for results, and optionally use type="date" for better browser-native date pickers:
<form id="dateForm"> <p>Van: <input type="date" id="fromDate" name="fromDate"> </p> <p>Tot: <input type="date" id="toDate" name="toDate"> </p> <button type="submit">Data invoeren</button> </form> <!-- Container to display results without page reload --> <div id="reservationResult" style="margin-top: 1rem; font-weight: bold;"></div>
Using type="date" ensures users input dates in a standard YYYY-MM-DD format, which avoids parsing errors later.
2. Add JavaScript for No-Refresh Submission
Add this script (either in a <script> tag at the end of your HTML body or an external JS file) to handle form submission, validate inputs, and send data to PHP via AJAX:
// Listen for form submit event document.getElementById('dateForm').addEventListener('submit', async function(e) { // Prevent default form refresh behavior e.preventDefault(); const fromDate = document.getElementById('fromDate').value; const toDate = document.getElementById('toDate').value; const resultContainer = document.getElementById('reservationResult'); // Frontend validation: check for empty fields if (!fromDate || !toDate) { resultContainer.textContent = "Geen datum geselecteerd"; resultContainer.style.color = "#dc3545"; return; } try { // Send data to PHP using Fetch API const response = await fetch('../app/src/dateValidation.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, // Encode data to avoid special character issues body: `fromDate=${encodeURIComponent(fromDate)}&toDate=${encodeURIComponent(toDate)}` }); // Get and display the PHP response const resultText = await response.text(); resultContainer.textContent = resultText; resultContainer.style.color = "#28a745"; } catch (error) { resultContainer.textContent = "Er is een fout opgetreden bij het verwerken van uw aanvraag."; resultContainer.style.color = "#dc3545"; console.error("Error:", error); } });
3. Adjust Your PHP Code
Update dateValidation.php to handle AJAX requests (no need to check for $_POST['submit'] anymore) and add better date validation:
<?php // Assume your $db connection is already set up here if (isset($_POST['fromDate']) && isset($_POST['toDate'])) { // Sanitize inputs (skip mysqli_real_escape_string if you don't need to save to DB) $fromDate = mysqli_real_escape_string($db, $_POST['fromDate']); $toDate = mysqli_real_escape_string($db, $_POST['toDate']); // Validate date validity $fromTimestamp = strtotime($fromDate); $toTimestamp = strtotime($toDate); if (!$fromTimestamp || !$toTimestamp) { echo "Ongeldige datum indeling. Gebruik de ingebouwde datumkiezer."; exit(); } // Ensure end date is not before start date if ($toTimestamp < $fromTimestamp) { echo "De einddatum moet na de begindatum liggen."; exit(); } // Calculate total reservation days (add +1 to include both start and end date) $dayDifference = floor(($toTimestamp - $fromTimestamp) / 86400) + 1; echo "U reserveert het product $dayDifference dagen."; } else { echo "Geen datumgegevens ontvangen."; } ?>
Key Notes
- If you don't need to save dates to a database, you can remove
mysqli_real_escape_stringand just use$fromDate = $_POST['fromDate']; - The
+1in the day calculation ensures a reservation from Jan 1 to Jan 2 counts as 2 days. Remove it if you want to count only the interval between dates. - The frontend validation gives users immediate feedback without waiting for a server response.
内容的提问来源于stack exchange,提问作者Frank

