"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > jQuery AJAX call to receive data error, but PHP has returned JSON

jQuery AJAX call to receive data error, but PHP has returned JSON

Posted on 2025-04-16
Browse:228

Why is jQuery\'s AJAX Call Receiving Incorrect Data Even Though PHP is Returning JSON?

PHP Returns JSON to jQuery AJAX Call

Despite your efforts to communicate with PHP through jQuery's AJAX functionality, you're continuously encountering the "selector activated" error. Additionally, the retrieved data appears incorrect. Let's delve into the issue and identify the potential cause.

PHP with JSON Return

The snippet provided below illustrates how to return JSON data in PHP:

header('Content-Type: application/json');
echo json_encode([
  'return' => 1,
  'msg1' => 'Message sent OK, we will be in touch ASAP'
]);
exit;

Notice the inclusion of header('Content-Type: application/json'); before echo to specify the JSON content type.

JavaScript and AJAX

Your JavaScript code below should handle the AJAX call successfully:

$('#msgid').html('

Submitting Form (External Routine)

'); if ($('#formEnquiry').valid()) { $("#msgid").append("

(Outside Ready) VALIDATED send to PHP

"); $.ajax({ url: "ContactFormProcess3.php", type: "POST", data: $('#formEnquiry').serialize(), dataType: "json", success: function (data) { alert("SUCCESS:"); for (var key in data) { $('#msgid').append(key); $('#msgid').append('=' data[key] '
'); } }, error: function (data) { alert("ERROR: "); for (var key in data) { $('#msgid').append(key); $('#msgid').append('=' data[key] '
'); } } }); } else { $('#msgid').append('

(Outside Ready) NOT VALIDATED

'); }

Ensure that your AJAX call triggers only after form validation to avoid unnecessary server requests.

Listed Supposed JSON Data

The output you're getting is not JSON formatted. It appears that jQuery's XHR object is being printed instead.

Potential Pitfalls

Verify the following:

  • Ensure that your PHP script is responding with the correct content type (Content-Type: application/json).
  • Make sure your AJAX call's dataType is set to "json".
  • Check that the script is executing successfully on the server, and that PHP is configured to handle JSON output.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3