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......
2 Answers 2
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;
?>
Comments
$_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.
6 Comments
selected field was not set. Please check with the developer tools of your browser that it is.htmlspecialchars when outputting JavaScript code. This will break it, and won't prevent XSS. Instead, if you use the JS variable to insert any text into the HTML document, you should HTML-encode the string at that point.(field name, field value) in the HTTP body. The developer tools of your browser depend ... on your browser. On Chrome, you get them with Ctrl+Shift+J, on Firefox, it's the Firebug extension, on Opera the built-in Dragonfly, and on Safari you can enable them under Settings->Advanced (on IE, it may be F12, but you're hopefully using another browser for web development). Go to the network tab and reload the site. Filter for XHR requests. By the way, multiple question marks are not necessary.
$_POST['selected']?$_POST['selected'](and in turn,$r) doesn't contain anything. Verify that whatever you are POSTing from is giving you what you are expecting.