Search code examples

Echo PHP variable from JavaScript?

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!

I am trying something like this:

  var areaOption=document.getElementById("<?php echo @$_POST['annonsera_name']?>");

Also I have tried this, but it only alerts a BLANK alert-box:

    alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck

Am I thinking completely wrong here?


Some PHP code:

        $test = "Hello World!";


  • In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set). As a rule, always use json_encode() as it will properly encode any PHP data type for javascript.

    Test this:

    alert (<?= json_encode($test);?>);