I'm using Php to get a background image.
The php script scans a directory and choose a random image:
$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".