Php Beginner
Php Beginner

Reputation: 61

Php within javascript : Not working

<script>
document.getElementById("comment").innerHTML="<?php echo 'foo bar'; ?>";
</script> 
<div id="comment"></div>

This should give the word "foo bar" in the div element,but its not.Do not know where i'm going wrong. Please help.

Upvotes: 0

Views: 238

Answers (2)

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

You are trying to use the comment element :

document.getElementById("comment").innerHTML="...";

Before it is declared :

<div id="comment"></div>

And firebug shows the following error :

   
(source: pascal-martin.fr)


You should :

  • First, create the element in your HTLM
  • And, only after, use it :
    • Either by changing the order you are doing things in your code,
    • Or waiting until the HTML page is fully loaded to execute Javascript.


If you choose the first solution, your code will look like this :

<div id="comment"></div>
<script>
    document.getElementById("comment").innerHTML="<?php echo 'foo bar'; ?>";
</script> 

And it will work :

  • The foo bar string will be visile
  • And there won't be any JS error anymore.

   
(source: pascal-martin.fr)

Upvotes: 2

SeanCannon
SeanCannon

Reputation: 78046

The script needs to go below the div, as it's trying to populate a div that hasn't been inserted into the DOM yet.

Upvotes: 1

Related Questions