0

Hi I have troubles to generate JSON with json_encode() PHP function. I have a .php file that is doing only following:

<?php
// include_once for a few files here

$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;

result is following:

{"number":"7"}

Then there is jQuery in another file, retrieving this by following code:

$(document).ready(function e() {
    let file_path = 'myJson.php';

    let json = $.getJSON(file_path);
    console.log(json);
    let json_obj = JSON.parse(json);

However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?

I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.

JohnyProkie
  • 389
  • 1
  • 6
  • 13
  • you can $.parseJSON() function. Look at here https://stackoverflow.com/questions/29917319/what-is-the-best-way-to-parse-a-php-array-into-javascript/29917406#29917406 – Pratik Gadoya Nov 29 '17 at 12:46
  • 1
    Don't parse `json`, jQuery has already done that for you. – jeroen Nov 29 '17 at 12:49
  • The point of having a dedicated method to download JSON is that it decodes it automatically. Otherwise it'd be useless. – Álvaro González Nov 29 '17 at 12:50
  • 1
    In your php script, add this at the top: `header("Content-Type: application/json; charset=utf-8");`. Also, `$.getJSON()` returns the `Promise`, not the parsed object. Check the docs for how to access the actual response. –  Nov 29 '17 at 12:51
  • @Chris G can you post this as answer? Was the most helpful one, would like to give you a credit. Thank you! – JohnyProkie Nov 29 '17 at 13:26

1 Answers1

0

If your web server sends JSON, it's good practice to set the Content-Type accordingly:

header("Content-Type: application/json; charset=utf-8");

On the client, you need to do:

$(document).ready(function() {
    $.getJSON('myJson.php', function(response) {
        // the response is already parsed by jQuery
        alert(response.number);
    });
}

$.getJSON() is asynchronous, so you need to pass a handler function to process the response.