Header json and the returned response
suggest changeSend a JSON body with a JSON content type:
<?php
$result = array('menu1' => 'home', 'menu2' => 'code php', 'menu3' => 'about');
//return the json response :
header('Content-Type: application/json'); // <-- header declaration
echo json_encode($result); // encode; do not pass true, which is the JSON_HEX_TAG flag
exit();
The header tells the client how to interpret the body. It does not change what json_encode returns.
If you are using UTF-8, you can use :
header("Content-Type: application/json;charset=utf-8");
jQuery parses the body as JSON when the response content type is application/json:
$.ajax({
url:'url_your_page_php_that_return_json'
}).done(function(data){
console.table(data);
console.log('Menu1 : ', data.menu1);
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents