Reputation: 3490
I expected that the number will increase on every alert, but it ended up being the same number which is 0.
Can I know why ?
I need to do this because in my real code, $wow represent the value I retrieved from server and I need to use javascript for loop to count the number element which I targeted.
How can i do this ?
Here is my Code :
<html>
<head>
<script>
<?php $wow = 0; ?>
for(var i =0; i < 4; i++){
alert("<?php echo $wow; ?>");
<?php $wow++; ?>
}
</script>
<body>
</body>
</html>
Upvotes: 0
Views: 67
Reputation: 816442
PHP is executed on the server side, JavaScript on the client side.
The way it works is like this:
Just have a look at the document source in the browser, there is no PHP in there because it was already executed (on the server).
What you can do instead is inject the value of the PHP variable into the JavaScript source code and manipulate the value with JavaScript:
var wow = <?php echo $wow; ?>
for(var i =0; i < 4; i++){
alert(wow);
wow++;
}
See also
Upvotes: 4
Reputation: 11104
php script is executed server side as per @Felix Kling comment..
dont define variable in php as php script executed server side not client side like javscript
u need to change script like ..
var wow = <?php echo $wow; ?>
for(var i =0; i < 4; i++){
alert("<?php echo wow; ?>");
<?php echo wow++; ?>
}
but there is no meaning to use/create variable via php script
you can just simply write like this
var wow = <?php echo $wow; ?>
for(var i =0; i < 4; i++){
alert(wow);
wow++;
}
Upvotes: 0
Reputation: 393
how about this one:
<html>
<head>
<script>
<?php
$wow = 0;
while($wow < 4){
echo "alert('" . $wow++ . "')";
}
?>
</script>
<body>
</body>
</html>
Upvotes: 0