I am getting some JSON data in JavaScript from a PHP file.
To use the data, I am using JSON.parse(json_response) which works except if I use a JSON header in my PHP:
header('Content-Type: application/json');
When used, I get the following message in console:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
At the moment I just choose between using the PHP header() or the JS JSON.parse() and found this useful question.
It looks like setting a JSON header "automatically parses" the JSON for my JS script.
- Is it a normal behaviour ? What may cause this ?
- What should I do ? Randomly choosing between
header()andJSON.parse()probably isn't a good idea.
Actual code:
index.chart.php:
<?php
header('Content-Type: application/json');
// [...] <- config lines, no output
// Dummy data for Chart.js
$data = [
'labels' => ['test', 'a', 'z', 'e', 'r', 't'],
'datasets' => [
[
'label' => 'First',
'backgroundColor' => 'rgb(63, 123, 249)',
'borderColor' => 'rgb(31, 117, 219)',
'data' => [
20, 10, 30, 45, 51.2, 5
],
'fill' => false
]
]
];
echo json_encode($data);
?>
index.chart.js:
window.addEventListener('DOMContentLoaded', function () {
// jQuery Ajax
$.get('assets/inc/index.chart.php').done(function (json) {
var response = JSON.parse(json);
console.log(response);
}).fail(function (error) {
window.console.log(error);
});
});
console.log(json)to see what exactly you get…? And if anything, the header doesn't parse the content, the header denotes that the content is in JSON format so jQuery automagically parses it for you.dataType)console.log(json)withoutJSON.parse(using PHPheader) outputs a well parsed JSON object. That would come from jQuery itself ?