How to run JavaScript code in PHP

Hello everyone,
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

The quotes in this part

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

don’t work correctly for PHP. You use single-quotes for the echo statement, but you close the second output string (just after the open-bracket after ChangeImage) and then immediately stick a double-quote in. I’m surprised you don’t get a parse error.

Basically you need to understand Javascript runs on the client side, and PHP runs or executes in the server side. If you want to put javascript code in a php file, remember you can write as you write html code inside php. You just follow the structure of an HTML file when you write a php file that returns a webpage. Just remember you are using php engine, so php is the main code to be executed on the server, so whatever inside php tags <?php ?> the server will execute that. I don’t know, maybe you want to made some tricks using php to control content of javascript, in that case

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.