Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change innerHTML with PHP?

Tags:

php

innerhtml

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>
like image 820
user2255325 Avatar asked Apr 07 '13 19:04

user2255325


People also ask

How do I get innerHTML in PHP?

php function DOMinnerHTML(DOMNode $element) { $innerHTML = ""; $children = $element->childNodes; foreach ($children as $child) { $innerHTML . = $element->ownerDocument->saveHTML($child); } return $innerHTML; } ?>

What is innerHTML in PHP?

The innerHTML() function presented in this page it is the equivalent of the innerHTML property from JavaScript. This function can be used in PHP to get the HTML content from a HTML element within a DOMDocument object.

What method is used to replace the innerHTML of an element?

Answer: Use the jQuery html() Method You can simply use the jQuery html() method to replace innerHTML of a div or any other element.

How do I add text to innerHTML?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.


1 Answers

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>
like image 62
Francisco Presencia Avatar answered Oct 26 '22 15:10

Francisco Presencia