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. 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:
<?php
$data = ["name" => "John Doe", "age" => 25];
header('Content-Type: application/json');
echo json_encode($data);
?>
jQuery side:
$.ajax({
url: 'your_php_script.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data); // {"name":"John Doe","age":25}
}
});
or
$.getJSON('your_php_script.php', function(data) {
console.log(data); // {"name":"John Doe","age":25}
});
Please note that, you need to make sure your jQuery version is compatible with your server PHP version.