Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
Dynamically Updating Image SRC using ES6

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" />
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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}`];
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!