How can I change innerHTML with PHP? [duplicate]
Asked Answered
T

1

8

I want to change the innerHTML with PHP code. But I cannot get it to work, and I do not understand why. I want it to change some text on the page but from another file. And so I thought that I could use this:

document.getElementById ("page"). innerHTML = "<? php echo $ home?>";

But it does not work.

Here is my code:

<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
    function ChangePage(page)
    {
       if(page == "home")
            {
            document.getElementById("page").innerHTML = "<?php echo $home ?";
            }
        }
</script>
Trenna answered 7/4, 2013 at 19:57 Comment(1)
For downvoters: Please consider adding a comment if you think this post can be improved.Sitsang
S
6

There are many small typos. Try removing the space between $ and 'home' and before 'php'. This is the right statement:

document.getElementById ("page"). innerHTML = "<?php echo $home?>";

Also, where's your closing php tag?

<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
    function ChangePage(page)
    {
       if(page == "home")
            {
            document.getElementById("page").innerHTML = "<?php echo $home; ?>";
            }
        }
</script>

Although this is a bad practice. Why would you want to do this instead of simply loading the php in the right place? Also, you do realize that 'page' should be the id of a pre-existing div in your html, right? Something like this would be better:

<html>
  <body>
    <div id = "page">
      <?php echo file_get_contents("home.php"); ?>
    </div>
  </body>
</html>
Sitsang answered 7/4, 2013 at 20:5 Comment(2)
I will use my navigation bar so when I press a button it will only change in my div with a id = page. I have more than just home.Trenna
From that comment I think what you are trying to do is dynamically retrieve the different sections of the page with javascript... you cannot do it in this way, PHP and JavaScript just don't work that way. PHP is ejecuted first in the server, then the page is downloaded and js can execute in the browser, but at that point PHP cannot execute (the browser doesn't execute PHP). Although something similar can be achieve through Ajax.Sitsang

© 2022 - 2024 — McMap. All rights reserved.