I have global JavaScript variable that is defined in PHP for use in a WordPress Block.
When the page initially loads, the "stars" image appears as expected. When a change event is fired, a 404 error appears in the console with "https://site.dev/img/var_set_in_php.imageSunset" as the URL instead of "https://site.dev/img/sunset.jpg".
How can this be updated to pull in the value that is set in PHP? I'm new to ES6, so hoping it's just something simple that I'm missing.
wp_localize_script(
'image-js',
'var_set_in_php', // Array containing dynamic data for a JS Global.
array(
'imageStars' => '/img/stars.jpg',
'imageSunset' => '/img/sunset.jpg',
)
);
function onChangeFunction(name) {
// name is set to "Sunset"
document.getElementById('image').src = `var_set_in_php.image${name}`;
}
<img src={var_set_in_php.imageStars} id="image" />
CodePudding user response:
I think you have a
var var_set_in_php = {
'imageStars' :'/img/stars.jpg',
'imageSunset' : '/img/sunset.jpg'
}
and if you do, you need this to access the object with a compound variable
document.getElementById('image').src = var_set_in_php[`image${name}`];