0
votes

When I echo the results in PHP, they seem to be correctly formatted as JSON, but when I echo the variable that holds them inside of JavaScript, I get an 'Uncaught SyntaxError: Unexpected identifier' error (which goes away when I remove the echo statement). Here is the code:

$charset="utf8";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}

$page = 'nike';
$stmt = $pdo->prepare('SELECT `url`, `alt`, `model`, `desc` FROM images WHERE page_id = (select id from pages where title = ?)');
$stmt->execute([$page]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'results are:' . $results; //array
$json = json_encode($results);
echo 'json is: ' . $json;// seemingly correct json formatted result set  

If I echo the $json variable directly inside of JavaScript like this:

var imgs="<?php echo $json; ?>";

I get an 'Uncaught SyntaxError: Unexpected identifier' error message, which disappears when I remove that line. My javascript function expects var imgs to be:

var imgs = [
    {"url": "images/adidas_large/1.png", "model": "Kumacross", "desc": ""},
    {"url": "images/adidas_large/2.png", "model": "fig 2 model", "desc": "fig 2 desc"},
    {"url": "images/adidas_large/3.png", "model": "fig 3 model", "desc": "fig 3 desc"},
    {"url": "images/adidas_large/4.png", "model": "fig 4 model", "desc": "fig 4 desc"},
    {"url": "images/adidas_large/5.png", "model": "fig 5 model", "desc": "fig 5 desc"},
    {"url": "images/adidas_large/6.png", "model": "fig 6 model", "desc": "fig 6 desc"},
    {"url": "images/adidas_large/7.png", "model": "fig 7 model", "desc": "fig 7 desc"},
    {"url": "images/adidas_large/8.png", "model": "fig 8 model", "desc": "fig 8 desc"},
    {"url": "images/adidas_large/9.png", "model": "fig 9 model", "desc": "fig 9 desc"}
];

... and works when supplied with this hard-coded. So my question is, how do I properly output the results of a PDO query in JSON format for use in a JavaScript function?

1

1 Answers

0
votes

I solved this by json_encoding $results in the javascript instead of the php and changing

var imgs = "<?php echo json_encode($results); ?>";

to

var imgs=<?php echo json_encode($results); ?>;