Home  >  Article  >  Backend Development  >  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?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 01:23:30774browse

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.

<code class="php"><?php

header('Content-Type: application/json');
touch('phpTouch.txt');
// process email
$email = 1;
if ($email) {
    $value = array('return' => 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;

?></code>

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.

<code class="javascript">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 />');
    }
}</code>

Solution

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

<code class="javascript">success: function (data) {
    alert("SUCCESS:");
    $('#msgid').append('Return: ' + data.return + '<br />');
    $('#msgid').append('Message: ' + data.msg1 + '<br />');
}</code>

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.

The above is the detailed content of How to properly handle JSON responses from PHP in a JQUERY AJAX call?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn