如何用AJAX POST方法提交表单双值至check.php(无页面刷新)
Solution for AJAX Form Submission Without Page Refresh
Let's get your form submitting data to check.php without reloading the page. I'll walk you through vanilla JavaScript (no libraries needed) and include a jQuery alternative if you prefer that.
First, here's the updated HTML form with AJAX functionality built in:
<!DOCTYPE html> <html> <head> <title>POLL</title> </head> <body> <!-- Add an ID to the form for easy targeting, and ensure inputs have matching names --> <form id="pollForm"> <input type="text" name="A" placeholder="Enter value for A"> <input type="text" name="B" placeholder="Enter value for B"> <button type="submit">Submit</button> </form> <!-- This div will display the response from check.php --> <div id="responseDisplay"></div> <script> // Grab references to the form and response area const pollForm = document.getElementById('pollForm'); const responseDisplay = document.getElementById('responseDisplay'); // Handle form submission pollForm.addEventListener('submit', function(e) { // Stop the default page refresh behavior e.preventDefault(); // Collect form data automatically const formData = new FormData(this); // Create the AJAX request const xhr = new XMLHttpRequest(); xhr.open('POST', 'check.php', true); // What to do when we get a response xhr.onload = function() { if (this.status === 200) { // Display the server's response responseDisplay.textContent = this.responseText; // If your check.php returns JSON instead of plain text, use this: // const serverResponse = JSON.parse(this.responseText); // responseDisplay.textContent = `Result: ${serverResponse.result}`; } else { responseDisplay.textContent = 'Oops! Something went wrong fetching the response.'; } }; // Handle network errors xhr.onerror = function() { responseDisplay.textContent = 'Network error: Could not connect to the server.'; }; // Send the form data to check.php xhr.send(formData); }); </script> </body> </html>
Your check.php Setup
Make sure your PHP script correctly retrieves the values and sends a response back. Here's a simple example:
<?php // Get the submitted values (use null coalescing to avoid undefined index errors) $A = $_POST['A'] ?? ''; $B = $_POST['B'] ?? ''; // Do your processing here (calculations, database calls, etc.) $response = "Success! Received values: A = $A, B = $B"; // Send the response to the AJAX request echo $response; // If you want to send JSON (better for structured data): // echo json_encode(['status' => 'success', 'message' => "A: $A, B: $B"]); ?>
Optional: jQuery Version (Shorter Code)
If you're already using jQuery in your project, this simplifies things:
<!-- Include jQuery first (add this in your head or before the script) --> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $('#pollForm').submit(function(e) { e.preventDefault(); // Send form data to check.php $.post('check.php', $(this).serialize(), function(response) { $('#responseDisplay').text(response); // For JSON responses: // $('#responseDisplay').text(`Status: ${response.status} | ${response.message}`); }).fail(function() { $('#responseDisplay').text('Error: Could not submit form.'); }); }); </script>
Key things to remember:
e.preventDefault()is critical—it stops the form from reloading the page like normal.FormData(or jQuery'sserialize()) collects all form inputs automatically, so you don't have to manually grab each value.- We added error handling to give users feedback if something goes wrong (network issues, server errors, etc.).
内容的提问来源于stack exchange,提问作者Alireza Etehadi
相关产品推荐
相关产品推荐

