提交表单后在当前页面弹窗展示PHP处理结果的实现方案
Got it, let's fix this so your form submits without redirecting and shows success/error messages right on the page using a popup. We'll use AJAX (with jQuery, since your form already uses jQuery UI for the budget slider) and modify the PHP handler to return clean JSON responses. Here's the step-by-step fix:
1. Update handler.php to Return JSON Responses
Instead of printing raw HTML, we'll send JSON data so our JavaScript can easily parse the result. Replace your existing handler.php code with this:
<?php header('Content-Type: application/json'); // Set response type to JSON if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "info@test.com"; $email_subject = "Your email subject line"; function sendError($error) { echo json_encode([ 'success' => false, 'message' => $error ]); exit; } // Validation: Check required fields exist if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['details'])) { sendError('We are sorry, but there appears to be a problem with the form you submitted.'); } $first_name = $_POST['name']; $email_from = $_POST['email']; $firma = $_POST['firma'] ?? ''; $telephone = $_POST['telefon'] ?? ''; $amount = $_POST['amount'] ?? ''; $comments = $_POST['details']; $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.<br />'; } $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$first_name)) { $error_message .= 'The Name you entered does not appear to be valid.<br />'; } if(!empty($firma) && !preg_match($string_exp,$firma)) { $error_message .= 'The Company Name you entered does not appear to be valid.<br />'; } if(strlen($comments) < 2) { $error_message .= 'The Project Description you entered does not appear to be valid.<br />'; } if(strlen($error_message) > 0) { sendError($error_message); } // Prepare email content $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "Name: ".clean_string($first_name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n"; $email_message .= "Company: ".clean_string($firma)."\n"; $email_message .= "Budget: ".clean_string($amount)."\n"; $email_message .= "Project Description: ".clean_string($comments)."\n"; // Send email $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); $mailSent = @mail($email_to, $email_subject, $email_message, $headers); if($mailSent) { echo json_encode([ 'success' => true, 'message' => 'Thank you for contacting us. We will be in touch with you very soon.' ]); } else { sendError('Sorry, something went wrong. Please try again later.'); } } else { sendError('No form data received.'); } ?>
Key Changes:
- Added
header('Content-Type: application/json')to tell the browser we're sending JSON instead of HTML. - Replaced the old
died()function withsendError()that returns a structured JSON error object. - Added JSON responses for both successful submissions and email send failures.
- Used null coalescing (
?? '') for optional fields to avoid "undefined index" PHP warnings.
2. Add AJAX Submission to index.html
Add this JavaScript code at the end of your index.html (right before the closing </body> tag) to handle form submission without redirecting:
<script> $(document).ready(function() { $('#my-form').submit(function(e) { e.preventDefault(); // Stop the form from redirecting to handler.php // Disable the submit button to prevent double clicks const submitBtn = $('#my-btn'); submitBtn.prop('disabled', true).html('Sending...'); // Collect all form data into a single string const formData = $(this).serialize(); // Send the data to handler.php via AJAX $.post('handler.php', formData, function(response) { // Re-enable the submit button submitBtn.prop('disabled', false).html('Senden <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span>'); // Show the feedback message in a popup (you can replace alert with a custom modal for better styling) alert(response.message); // If submission was successful, reset the form and slider if(response.success) { $('#my-form')[0].reset(); $('#slider-range-min').slider('value', 1); $('#amount').val(''); } }, 'json') .fail(function() { // Handle cases where the AJAX request fails (e.g., network issues) submitBtn.prop('disabled', false).html('Senden <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span>'); alert('Sorry, there was an error connecting to the server. Please try again.'); }); }); }); </script>
Key Features:
e.preventDefault()stops the default form redirect behavior.$(this).serialize()automatically collects all form fields into a format that's easy to send via AJAX.- We disable the submit button during submission to prevent users from clicking multiple times.
- The response from PHP is parsed as JSON, so we can easily access
successandmessageproperties. - On success, we reset the form and the budget slider to their initial states.
3. Verify Dependencies
Make sure your page includes jQuery and jQuery UI (since you're using the budget slider, you probably already have these included in your site's scripts). If not, add the local versions of these libraries to your page before the custom script we added.
That's all! Now when users submit the form, they'll stay on the same page and see a popup with the success or error message from your PHP handler.
内容的提问来源于stack exchange,提问作者user8432496

