Search code examples
javascriptphpdominnerhtml

.innerHTML to echo PHP variable


When i try to set my <span> to PHP variable, it sends it commented. The file is saved as .php and is served by apache2.4 from localhost

document.getElementById('displayName').innerHTML = " <?php echo $_SESSION['user']; ?>";

This is what i see in browser when inspecting:

<!--?php echo $_SESSION['user']; ?-->

Solution

  • You can't run PHP code with JavaScript. When the user receives the page, the server will have evaluated and run all PHP code, and taken it out.