WordPress自定义模板模态框表单AJAX无刷新提交失败求助
Fix for AJAX Form Submission Refreshing the Page in Modal
Looks like your form is still refreshing because there are a few critical issues in your JavaScript code that are preventing the AJAX flow from working correctly. Let me break down the problems and share the fixed version:
Key Issues in Your Original Code
- Wrong event binding: You’re listening for clicks on
.button, but your submit button uses the ID#form-submit. Even worse, you should listen to the form’ssubmitevent instead of the button click—this covers all submission triggers (like pressing Enter). - Mismatched variable names: Your validation logic uses inconsistent variable names (e.g., assigning
lastNameto anamevariable then checking againstlastName), which breaks validation and lets the form submit normally. - AJAX code placed outside the event handler: Your AJAX request wasn’t actually running when the form was submitted because it was outside the click event scope.
- Failed to block default form behavior: The
return falsewas in the wrong place, so the browser still executed the default form submit (which causes the refresh). - Incomplete/unsafe data string: Manual data string concatenation missed the
firstNamefield and risks encoding issues.
Fixed Full Code
HTML (no changes needed, just keeping it for reference)
<form method="POST" action="" name="modalForm" id="modalForm" enctype="multipart/form-data" autocomplete="off"> <input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required> <label class="error" for="name" id="lastName_error">This field is required.</label> <input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required> <label class="error" for="name" id="firstName_error">This field is required.</label> <input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required> <label class="error" for="email" id="email_error">This field is required.</label> <span class="validation-text">Please enter a valid email address.</span> <input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" required> <label class="error" for="contactNumber" id="contactNumber_error">This field is required.</label> <input type="submit" name="submit" value="Submit" id="form-submit"> </form>
Fixed JavaScript
(function($) { // Hide error messages on page load $('.error').hide(); $('.validation-text').hide(); // Listen to the form's submit event (covers all submission ways) $('#modalForm').on('submit', function(e) { // Block the browser's default form submit behavior (critical to stop refresh) e.preventDefault(); // Reset error states $('.error').hide(); $('.validation-text').hide(); let isValid = true; // Get field values with proper trimming const lastName = $.trim($("#lastName").val()); const firstName = $.trim($("#firstName").val()); const email = $.trim($("#Email").val()); const contactNumber = $.trim($("#contactNumber").val()); // Validate Last Name if (lastName === "") { $("#lastName_error").show(); $("#lastName").focus(); isValid = false; } // Validate First Name if (firstName === "") { $("#firstName_error").show(); $("#firstName").focus(); isValid = false; } // Validate Email (required + format) const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (email === "") { $("#email_error").show(); $("#Email").focus(); isValid = false; } else if (!emailRegex.test(email)) { $('.validation-text').show(); $("#Email").focus(); isValid = false; } // Validate Mobile Number (required + format) const phoneRegex = /^09\d{9}$/; if (contactNumber === "") { $("#contactNumber_error").show(); $("#contactNumber").focus(); isValid = false; } else if (!phoneRegex.test(contactNumber)) { $("#contactNumber_error").text("Please enter a valid mobile number.").show(); $("#contactNumber").focus(); isValid = false; } // Proceed with AJAX only if validation passes if (isValid) { // Use serialize() to auto-collect all form data (safer than manual string concat) const formData = $(this).serialize(); $.ajax({ type: "POST", url: "/wordpress-page/", // Make sure this points to your actual PHP processing page data: formData, success: function() { // Replace form with thank you message $('#modalForm').html("<div id='message'></div>"); $('#message') .html("<h2>Contact Form Submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); }, error: function() { // Handle AJAX failure gracefully $('#modalForm').html("<div id='message'></div>"); $('#message') .html("<h2>Oops!</h2>") .append("<p>There was an error submitting your form. Please try again later.</p>") .hide() .fadeIn(1500); } }); } return false; // Extra safety to block default behavior }); // Ensure the number-only input function is globally accessible window.isNumberKey = function(evt) { const charCode = evt.which ? evt.which : evt.keyCode; return !(charCode > 31 && (charCode < 48 || charCode > 57)); }; })(jQuery);
Additional Notes
- File Uploads: If you’re actually using file uploads (your form has
enctype="multipart/form-data"), replace theserialize()part withFormDatato handle files:const formData = new FormData(this); // Update AJAX settings: $.ajax({ // ... other settings data: formData, contentType: false, // Required for FormData processData: false, // Required for FormData // ... success/error }); - PHP Processing: Make sure your
/wordpress-page/endpoint correctly handles POST data and doesn’t output any extra whitespace or HTML—this could break the AJAX response.
内容的提问来源于stack exchange,提问作者indigo
相关产品推荐
相关产品推荐

