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:
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