wel
wel

Reputation: 11

how to pass a php values to javascript?

here is the code??

posting code:

$.post('get.php',{selected:"aaaa"},function(return){alert(return);});

when i check the values of "selected" value using

<?php

$r=$_POST['selected'];
echo $r;

?>

is displays the value "aaaa" correctly..

this code works fine...

<?php 

$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";

when we echo the value"welcome" it is stored in the variable answer.and i could print that...

but when i put like this....

<?php 

$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";

an empty value is stored in answer... and nothing gets displayed....

whether specifying $r inside " " is not right... how to specify that......

Upvotes: 1

Views: 589

Answers (2)

phihag
phihag

Reputation: 288300

$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).

Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:

var answer = <?php echo json_encode($_POST['selected']); ?>

Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.

Upvotes: 1

jeroen
jeroen

Reputation: 91792

Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:

javascript in original page:

$.post('get.php',{selected:"aaaa"},function(data){
  var answer = data;
});

get.php

<?php
  $r=$_POST['selected'];
  echo $r;
?>

Upvotes: 1

Related Questions