Home >Backend Development >PHP Tutorial >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:
<code class="php">header('Content-Type: application/json'); echo json_encode([ 'return' => 1, 'msg1' => 'Message sent OK, we will be in touch ASAP' ]); exit;</code>
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:
<code class="javascript">$('#msgid').html('<h1>Submitting Form (External Routine)</h1>'); if ($('#formEnquiry').valid()) { $("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>"); $.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] + '<br />'); } }, error: function (data) { alert("ERROR: "); for (var key in data) { $('#msgid').append(key); $('#msgid').append('=' + data[key] + '<br />'); } } }); } else { $('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>'); }</code>
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:
The above is the detailed content of Why is jQuery\'s AJAX Call Receiving Incorrect Data Even Though PHP is Returning JSON?. For more information, please follow other related articles on the PHP Chinese website!