Reputation: 181
how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
Upvotes: 0
Views: 2152
Reputation: 73
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php
Upvotes: 0
Reputation: 1894
like this if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
Upvotes: 0
Reputation: 1202
it is not possible because both are different languages so you cant use javascript varible in php inside javascript
Upvotes: 1
Reputation: 209
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
Upvotes: 0
Reputation: 151588
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x
.
Upvotes: 0
Reputation: 9311
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
Upvotes: 1
Reputation: 66389
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x
from querystring and send proper output.
Upvotes: 1