dramasea
dramasea

Reputation: 3490

Why php variable cant work with javascript loop?

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

Answers (3)

Felix Kling
Felix Kling

Reputation: 816442

PHP is executed on the server side, JavaScript on the client side.

The way it works is like this:

  1. browser makes request
  2. server receives request
  3. server executes PHP
  4. server sends response/HTML
  5. browser receives response/HTML
  6. browser parses HTML / executes JS.

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

Anant Dabhi
Anant Dabhi

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

YouSer
YouSer

Reputation: 393

how about this one:

<html>
<head>
<script>
<?php
    $wow = 0;
    while($wow < 4){
        echo "alert('" . $wow++ . "')";
    }
?>
</script>
<body>
</body>
</html>

Upvotes: 0

Related Questions