PHP+Ajax+jQuery联系表单JSON解析语法错误求助
Hey there! Let's break down this JSON parsing error you're facing—it's one of the most common gotchas when building AJAX contact forms, so we'll get to the bottom of it quickly.
What's Causing the Unexpected token < Error?
This error means your enviar.php script is not returning valid JSON—instead, it's sending back content that starts with a < character. 9 times out of 10, this is either:
- A PHP error message (like a
NoticeorWarningwrapped in HTML) - Accidental whitespace/line breaks at the start/end of your PHP file
- HTML content (like a DOCTYPE tag or partial page) from a misplaced include/require
Step-by-Step Troubleshooting
1. First, See What Your Server Is Actually Sending
Open your browser's DevTools (F12), go to the Network tab, then submit your contact form. Find the request to enviar.php, click into it, and check the Response tab. You’ll immediately see what’s breaking the JSON—look for any HTML tags, error messages, or random text before/after the JSON.
2. Fix Your enviar.php Output
Your PHP script should only output clean JSON, with no extra content. Here’s a corrected structure to follow:
<?php // Disable error output (we'll handle errors internally instead of dumping them to the page) error_reporting(0); ini_set('display_errors', 0); // Set the correct JSON response header (critical for jQuery to parse it properly) header('Content-Type: application/json'); // Sanitize and retrieve form data $name = $_POST['name'] ?? ''; $email = $_POST['email'] ?? ''; $message = $_POST['message'] ?? ''; // Initialize response data $response = [ 'success' => false, 'message' => '' ]; // Validate form fields if (empty($name) || empty($email) || empty($message)) { $response['message'] = 'Please fill in all required fields.'; } else { // Add your email-sending logic here (e.g., using mail() or a library like PHPMailer) $mailSent = mail('your-email@example.com', 'New Contact Form Submission', $message, "From: $name <$email>"); if ($mailSent) { $response['success'] = true; $response['message'] = 'Your message was sent successfully!'; } else { $response['message'] = 'Oops, something went wrong sending your message.'; } } // Output only the JSON, no extra characters! echo json_encode($response); exit; // Ensure no additional code runs after this ?>
- Critical Notes:
- Remove any whitespace/line breaks before the opening
<?phptag—these get sent as output and break JSON. - If you’re including other PHP files, make sure those files don’t output anything (no echo statements, no HTML comments).
- Remove any whitespace/line breaks before the opening
3. Clean Up Your jQuery/AJAX Code
Let jQuery handle JSON parsing automatically instead of using JSON.parse() manually. Here’s a solid example:
$(document).ready(function() { $('#your-contact-form-id').submit(function(e) { e.preventDefault(); // Stop the default form submission $.ajax({ url: 'enviar.php', type: 'POST', data: $(this).serialize(), // Serialize form data correctly dataType: 'json', // Tells jQuery to expect and parse JSON automatically success: function(res) { // Handle the response from PHP if (res.success) { alert(res.message); // Optional: Reset the form $('#your-contact-form-id')[0].reset(); } else { alert('Error: ' + res.message); } }, error: function(xhr) { // If parsing fails, log the raw response to debug console.log('Raw server response:', xhr.responseText); alert('Something went wrong with the request. Check the console for details.'); } }); }); });
- Avoid manual
JSON.parse()unless you’re 100% sure the response is valid JSON—jQuery’sdataType: 'json'is far more reliable.
4. Check Foundation 6 Interference
Foundation’s form components might add default behaviors that interfere with AJAX. Try temporarily disabling Foundation’s form JavaScript, test the AJAX submission, and re-enable it gradually to see if that’s the issue.
Final Tip
If you’re still stuck, copy the raw response from the Network tab and paste it into a JSON validator—it’ll show you exactly where the invalid content is.
内容的提问来源于stack exchange,提问作者atole

