"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 > How to properly handle JSON responses from PHP in a JQUERY AJAX call?

How to properly handle JSON responses from PHP in a JQUERY AJAX call?

Published on 2024-11-24
Browse:134

How to properly handle JSON responses from PHP in a JQUERY AJAX call?

PHP Returning JSON to JQUERY AJAX Call

This question tackles the integration of PHP, JQUERY, and AJAX for form processing and returning responses in JSON format.

PHP Implementation

The PHP code provided includes the necessary functions for processing the form and handling email sending. To return JSON, it uses json_encode to convert an array into a JSON string. The array contains a return key for success/failure indication and a msg1 key for message display.

 1, 'msg1' => 'Message sent OK, we will be in touch ASAP');
} else {
    $value = array('return' => 0, 'msg1' => 'Message Failed, please try later');
}
$output = json_encode($value);
echo $output;

?>

JQUERY and AJAX

The JQUERY code handles form validation and AJAX communication. It uses the success and error callbacks to handle the response from the PHP script. However, the code displays the raw data object instead of extracting and displaying the specific JSON values.

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] '
'); } }

Solution

To display the JSON values correctly, modify the success callback to extract the return and msg1 values from the JSON response:

success: function (data) {
    alert("SUCCESS:");
    $('#msgid').append('Return: '   data.return   '
'); $('#msgid').append('Message: ' data.msg1 '
'); }

With these adjustments, the code should correctly process the form, return the JSON response from PHP, and extract and display the return and msg1 values.

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