使用AJAX获取表单数据经PHP校验存库时遇JSON解析错误
Hey, let's break down this error you're hitting. That message means your frontend JavaScript is trying to parse the response from your PHP script as JSON, but the PHP side isn't sending valid JSON—instead, it's sending a plain string that starts with an "s" (like "Success!" or "Something went wrong..."), which breaks the JSON parser.
Here's how to fix this step by step:
1. First, see exactly what your PHP script is returning
Before you fix anything, you need to confirm what the backend is sending. Add an error callback to your AJAX request to log the raw response, or check the Network tab in your browser's dev tools:
$(".d-f-sub").on('click',function(e){ e.preventDefault(); resetErrors(); $('.inputTxtError').children('form input').css({'border-color' : '','box-shadow' : ''}); var data = {}; $.each($('form input, form select'), function(i, v) { if (v.type !== 'submit') { data[v.name] = $(v).val(); } }); $.ajax({ url: 'your-php-script.php', // Replace with your actual PHP file path type: 'POST', data: data, dataType: 'json', // You told jQuery to expect JSON here success: function(response) { // Your existing success logic }, error: function(xhr, status, error) { // Log the raw response to see what PHP is sending console.log('Raw PHP response:', xhr.responseText); console.log('Error details:', error); } }); });
Chances are you'll see a plain string like "Data saved successfully!" instead of a proper JSON object.
2. Fix your PHP script to send valid JSON
Your PHP code needs to output strict, valid JSON every time—no random echo statements, no extra whitespace, just properly formatted JSON with the right header.
Example of a valid success response:
// After validating input and saving to the database $response = [ 'status' => 'success', 'message' => 'Data stored successfully' ]; // Set the correct content type header header('Content-Type: application/json'); // Encode and output the JSON echo json_encode($response); // Exit immediately to prevent any extra output exit;
Example of a valid error response (for validation failures):
// If input validation fails $response = [ 'status' => 'error', 'message' => 'Please fix the following issues:', 'errors' => [ 'email' => 'Email is required', 'password' => 'Password must be at least 8 characters' ] ]; header('Content-Type: application/json'); echo json_encode($response); exit;
⚠️ Critical note: Make sure there's no extra output in your PHP script. That includes:
- Spaces or newlines before the opening
<?phptag - Accidental
echoorvar_dump()statements used for debugging - Extra whitespace in included/required files
Even a single space before <?php will break the JSON. If you're struggling with this, you can add ob_start(); at the very top of your PHP script and ob_end_clean(); right before echo json_encode(...) to suppress accidental output.
3. Update your frontend to handle the JSON response
Once your PHP is sending valid JSON, you can clean up your frontend success callback to use the structured data:
success: function(response) { if (response.status === 'success') { alert(response.message); // Optional: Reset the form after success $('form')[0].reset(); } else { // Handle validation errors (call your resetErrors/showErrors functions here) showErrors(response.errors); } }
Common mistakes to watch out for
- Forgetting to set the
Content-Type: application/jsonheader in PHP: jQuery might still parse it, but it's not standard and can cause issues. - Sending plain text instead of JSON from PHP: Even if it's a success message, wrap it in a JSON object.
- Having
dataType: 'json'in your AJAX request but not sending JSON from PHP: This is the direct cause of your error.
内容的提问来源于stack exchange,提问作者Yordan Yordanov

