0

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>
Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
dramasea
  • 3,370
  • 16
  • 49
  • 77
  • 6
    PHP is executed on the server side, JavaScript on the client side. The way it works is like this: browser makes request `->` server receives request `->` server executes PHP `->` server sends response/HTML `->` browser receives response/HTML `->` 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). – Felix Kling Mar 27 '14 at 05:58
  • Known as the [Client-Server Model](http://en.wikipedia.org/wiki/Client%E2%80%93server_model) – elclanrs Mar 27 '14 at 05:59
  • 2
    @FelixKling:- You can post this as an answer rather than comment. I will surely upvote! – Rahul Tripathi Mar 27 '14 at 06:00
  • 2
    I feel like there needs to be a community wiki question and answer addressing this problem that we can palm these questions off to. – Marty Mar 27 '14 at 06:06

3 Answers3

4

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

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

how about this one:

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

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++;
        }
Anant Dabhi
  • 10,864
  • 3
  • 31
  • 49