Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Problem between PHP and JavaScript with json

15 views
Skip to first unread message

Une Bévue

unread,
May 5, 2017, 4:08:04 AM5/5/17
to
I'm using Php to get a background image.
The php script scans a directory and choose a random image:


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

[...]

$dir = '/Users/yt/Sites/global/backgrounds';
$files = array();
chdir($dir);
foreach (glob("*.jpg", GLOB_NOSORT) as $filename) {
$files[] = $filename;
}
foreach (glob("*.png", GLOB_NOSORT) as $filename) {
$files[] = $filename;
}
$count = count($files);
$rand = rand(0, $count);
$background = '/global/backgrounds/'. $files[$rand];


Then the script sends that to Javascript using json_encode( $data ) :

$data['text'] = 'html {
background: transparent url(http://mbp.local/global/backgrounds/'.
$files[$rand] . ') no-repeat center center fixed;background-size: cover;}';
$data['background'] = 'transparent
url(http://mbp.local/global/backgrounds/'. $files[$rand] . ') no-repeat
center center fixed';
$data['background-image'] =
'url(http://mbp.local/global/backgrounds/'. $files[$rand] . ')';
$data['backgroundSize'] = 'cover';
echo json_encode( $data );

The JavaScript call this script like that :

JSON.fetch = function(url, callback) {
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (json) {
callback(json);
});
};

used as :
getBackground () {
JSON.fetch("http://mbp.local/php/background-json.php",
this.setBackground);
};

with the callback :


setBackground(json) {
if(json.hasOwnProperty('background-image')) {
document.body.style.backgroundImage = json['background-image'];
}
};

This is working well however, in the browser console I get this error :
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the
JSON data [Learn More]

The "[Learn More]" is link to this MDN page :
SyntaxError: JSON.parse: bad parsing
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/JSON_bad_parse?utm_source=mozilla&utm_medium=firefox-console-errors&utm_campaign=default>



I don't know how to debugg that, that's to say how to get the raw json
from the PHP script "background-json.php".



Note that even using :
$ wget http://mbp.local/php/background-json.php

i get (shortened) :

{"text":"html { \n backgro [...]

i verify enconding (being us-ascii then also utf-8)

there is no bom reading that downloaded file in an hex editor gives :
the firsts characters :
7B227465 - {"te

the lasts ones :
76657222 7D - ver"}

following :
<http://www.asciitable.com/>
7B is correct for {
7D is correct for }

then, I'm lost...
0 new messages