-1

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 ()

ManelPNavarro
  • 579
  • 7
  • 21

3 Answers3

1

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.

v_kovit_v
  • 34
  • 6
0

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>
Mohit
  • 776
  • 7
  • 13
-1

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>
  • That's completely wrong. You can't read PHP like this. Also, `language` attribute is deprecated, `type` is optional. – Raptor Feb 10 '14 at 09:22
  • True about both attributes, even though that's not the point. Yes, you can read it, as long as you set the correct header http://www.javascriptkit.com/javatutors/externalphp.shtml. – Paolo Tozzo Feb 10 '14 at 09:26
  • @ShivanRaptor Certainly this is doable. As long as `yourscript.php` outputs javascript. That is a quite common solution to create specific js snippets, actually. Though I agree that is has nothing to do with this question. – arkascha Feb 10 '14 at 09:28
  • Agree with both of you, as long as PHP has `text/javascript` as Content Type, it can be used as JavaScript. – Raptor Feb 10 '14 at 09:30