How to run JavaScript code in PHP

The following HTML/JavaScript code inserts a background imag to a div without causing problems.

<!DOCTYPE html>
<html lang = "en">
<head>
  <title>to-forum.html</title>
  <script>
    function ChangeImage(param)
    { 
      return("http://localhost/images/greensilver.gif");
    }
  </script>
</head>
<body>
  <div id="logo" style = "height:400px; width:400px";> 
    <script>
      var xyz = ChangeImage();
      document.getElementById("logo").style.backgroundImage = "url('" + xyz + "')";
    </script>
  </div>
</body>
</html>

I need to run that JS script from a PHP code so I wrote:

<!DOCTYPE html>
<html lang = "en">
<head>
  <script>
    function ChangeImage(param)
    { 
      return("http://localhost/tlushim/images/greensilver.gif");
    }
  </script>
</head>
<body>
  <div id="logo" style = "height:400px; width:400px";> 
    <?php
      echo '<script>',
      'var xyz = ChangeImage"('" + 1 + "')";',
      'document.getElementById"('" + logo +"')".style.backgroundImage = "url('" + xyz + "')";',
      '</script>'
    ?>
  </div>
</body>
</html>

With the second code I was less lucky/ This time the desired background image didn't show up, probably, because I dont know how to run JS code from PHP. Could anyone help me with that please? Thanks

3 answers

  • answered 2017-06-17 18:16 abinmorth

    try using . for concatenation instead of , and +
    also escape the double quotes with \

  • answered 2017-06-17 18:16 derHugo

    The element might still not be loaded when your code is executed so nothing happens.

    use something like

    document.onload=function (){...};
    

    around your function.

  • answered 2017-06-17 18:16 duskwuff

    <?php
      echo '<script>',
      'var xyz = ChangeImage"('" + 1 + "')";',
                              ^
    

    The single quotation mark I've marked above ends the PHP string. The double quotation mark following it is unexpected, and causes a syntax error.

    Using PHP to echo out Javascript code is pointless here. If you insist, though, you can use herestring syntax to avoid the quoting issue:

    <?php echo <<<EOS
    <script>
        var xyz = ChangeImage();
        document.getElementById("logo").style.backgroundImage = "url('" + xyz + "')";
    </script>
    EOS;
    ?>