Pergunta

I'm trying to pass a php var that is a string using Javascript, but in the final result the string gets cmmented in html. Here's my code:

PHP:

$txtVar = "My text";

JavaScript:

var txt = '<?php echo $txtVar; ?>';
document.getElementById('MyDiv').innerHTML = txt;

HTML(result):

<div id="MyDiv"><!--?php echo $txtVar ; ?--></div>

I just want the string value to be printed in my html, withou the comments ()

Foi útil?

Solução

First print the PHP variable value in another HTML entity like hidden input HTml tag and after that pick the hidden value using JavaScript and assign into your desire tag.

  1. In Your page.

    <input type="hidden" value="<?php echo $txtVar; ?>" id="phptext" name="phptext" />
    
  2. JavaScript code:

document.getElementById('MyDiv').innerHTML = document.getElementById('phptext').value;

This is works.

Outras dicas

Here is your answer.

<?php
$txtVar = "My text";
?>

<div id="MyDiv"></div>

<script>
var txt = "<?php echo $txtVar; ?>";
var element = document.getElementById('MyDiv');
element.innerHTML = txt;
</script>

If your javascript is an external file, you can just rename it with .php extension, and then retrieve it with

<script language='javascript' type='text/javascript' src='yourscript.php'></script>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top