W3docs

PHP returning JSON to JQUERY AJAX CALL

To return JSON from a PHP script to a jQuery AJAX call, you can use the json_encode() function in PHP to convert an array or object into a JSON string.

To return JSON from a PHP script to a jQuery AJAX call, you can use the json_encode() function in PHP to convert an array or object into a JSON string. Then, in the PHP script, you can use the header() function to set the "Content-Type" to "application/json" and echo the JSON string.

On the jQuery side, you can use the $.ajax() or $.getJSON() method to make the AJAX call and handle the JSON data returned from the PHP script.

Example: PHP side:

Example of JSON data returned from the PHP script

<?php
$data = ["name" => "John Doe", "age" => 25];
header('Content-Type: application/json');
echo json_encode($data);
?>

jQuery side:

Example of using the $.ajax() method to make the AJAX call

$.ajax({
    url: 'your_php_script.php',
    type: 'GET',
    dataType: 'json',
    success: function(data) {
        console.log(data); // {"name":"John Doe","age":25}
    },
    error: function(xhr, status, error) {
        console.error('AJAX Error:', status, error);
    }
});

or

Example of using the $.getJSON() method to make the AJAX call

$.getJSON('your_php_script.php', function(data) {
    console.log(data); // {"name":"John Doe","age":25}
})
.fail(function(xhr, status, error) {
    console.error('AJAX Error:', status, error);
});