0

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() and JSON.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);
    });

});
AymDev
  • 6,626
  • 4
  • 29
  • 52
  • I just use json_encode() and it works without issue... unsure why you get an error with one but not the other... seems like an error potentially... can you get the result of the script from the network tab of your browser? – Adam Aug 22 '18 at 14:31
  • `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. – deceze Aug 22 '18 at 14:32
  • _"Is it a normal behaviour ? What may cause this ?"_: _"If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, **in 1.4 JSON will yield a JavaScript object**, in 1.4 script will execute the script, and anything else will be returned as a string)"_ ([Source (-> `dataType`)](http://api.jquery.com/jquery.ajax/) – Andreas Aug 22 '18 at 14:38
  • @deceze `console.log(json)` without `JSON.parse` (using PHP `header`) outputs a well parsed JSON object. That would come from jQuery itself ? – AymDev Aug 22 '18 at 14:40

2 Answers2

4

If you don't specify a dataType then jQuery will determine what type of data is received from a URL using the Content-Type header and run it through an appropriate parser.

json is not a string of JSON, it is a JavaScript object that you got from parsing the JSON.

The input to JSON.parse needs to be a string of JSON.

Change:

function (json) {
    var response = JSON.parse(json);

To:

function (response) {
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Is it a normal behaviour ? What may cause this ?

Yes, this is normal behavior, jQuery.ajax has converters that are used to automatically run certain functions on the returned data. For requests that return JSON headers, that is jQuery.parseJSON, meaning, that the data that gets passed to the callback function is already parsed JSON.

What should I do ? Randomly choosing between header() and JSON.parse() probably isn't a good idea.

You are right, that would only make your code harder to follow. Choose one and keep it throughout the project. If you are currently using other services for example, that don't have the right headers set up for JSON, I would suggest always using JSON.parse and not using the header function here.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44