Echo PHP variable from JavaScript?

I have a PHP page with some JavaScript code, but this JavaScript code below works, or maybe I'm leaving!

I am trying something like this:

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

I also tried this, but it only warns the BLANK alert-box:

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

I think that is completely wrong here?

UPDATE

Some PHP codes:

  <?php $test = "Hello World!"; ?> 
+4
source share
6 answers

In your second example, you are missing quotation marks around the string (therefore, H is interpreted as a variable that you did not set).

Check it:

 alert (<?php echo "'H'";?>); 

OR

 alert ('<?php echo "H";?>'); 
+7
source

PHP runs on the server side, while Javascript runs on the client side.

The process is that PHP generates Javascript that will be executed on the client side.

You should be able to verify the generated JS just by looking at the code. Of course, if JS relies on some PHP variables, they must be instanciated before JS output.

 <?php $test = 'Hello world'; ?> <html> <body> <script> alert('<?php echo $test; ?>'); </script> </body> </html> 

will work but

 <html> <body> <script> alert('<?php echo $test; ?>'); </script> </body> </html> <?php $test = 'Hello world'; ?> 

will not be

+5
source

Use json_encode to convert some text (or any other data type) to a JavaScript literal. Don't just put quotes around the echo line - what if the line contains a quote or a new line or backslash? The best case is when your code crashes, in the worst case you have a big old script security hole.

So,

 <?php function js($o) { echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); } ?> <script type="text/javascript"> var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>); areaOption.selected= true; alert (<?php js('Hello World'); ?>); </script> 
+3
source

Your use of @$_POST means that you received (or expect) errors - check your generated source to see if the value was entered correctly. Otherwise, document.getElementById will fail and you will not get an exit.

0
source
  alert("Delete entry <? echo $row['id']; ?> ") 
0
source

If your extension is js, php will not work in this file.

The reason is that php parses the files it should use. The types of files that php will handle are configured in httpd.conf using AddType commands (or directives, regardless of what they call).

So, you have 3 options:

  • add filetype js to the list of files that php will handle (BAD, VERY BAD)
  • insert script embedded in php file
  • rename the file to script.js.php, and at the beginning of the file specify the type of content, for example:

    <? php header ('content-type: text / javascript') ;? >

Hooray!

0
source

All Articles