How to insert php value inside javascript?

I want to load an image with a PHP function inside the following JavaScript function (common.js)

$(".header").css('background', function () {
  var bg = ('url('+ '<?php get_image_url(); ?>'+') center / cover no-repeat #000');
  return bg;
});

the PHP function ‘get_image_url()’ doesn’t run.

You can’t do this in a JavaScript file. You can’t execute PHP inside of JavaScript.

If you need a particular image that you don’t have at build time, you can approach that in a couple ways, but they’ll generally all involve printing out the data you need into HTML through your template, and then getting that information with JavaScript. One example might be:

// your PHP template
<header class="header" data-background="<?php echo get_image_url(); ?>">
   // some content
</header>
// common.js
$header = $(`.header`);
$header.css(`background`, `url(${$header.data('background')}) center / cover no-repeat #000`);

If the code you posted is all you need to do with that data, though, it might be easier (and more performant) to just print that out as an inline style in your template:

// your PHP template
<header class="header" style="background: url(<?php echo get_image_url(); ?>) center / cover no-repeat #000">
   // some content
</header>
1 Like