-1

I am trying to increment a php variable in a javascript function:

function border(){
  <?php $var_drafts_display=0; ?>;
  for(var i=0; i<5; i++)
     {
    <?php ++$var_drafts_display ; ?>;
     }
  var final_num='<?php  echo $var_drafts_display; ?>';
  alert(final_num);
  }

But the php variable gets incremented only once i.e alert(final_num) shows 1. I know php is server side program and javascript is client side program, is that the main problem why php variable is not getting incremented. Also, I am not able to figure out why it is getting incremented only once.

Blue
  • 22,608
  • 7
  • 62
  • 92
Sagar
  • 33
  • 6
  • You cannot increment a php variable in javascript without ajax. Your javascript is just text to php. You need to understand the difference between server side and client side code, and how they interact. – kennasoft Aug 13 '16 at 09:32

3 Answers3

6

You're trying to mix server side code (PHP) with JavaScript code:

function border(){
  <?php $var_drafts_display=0; ?>;
  for(var i=0; i<5; i++)
     {
    <?php ++$var_drafts_display ; ?>;
     }
  var final_num='<?php  echo $var_drafts_display; ?>';
  alert(final_num);
  }

will ultimately get turned into this:

function border(){
      ;
      for(var i=0; i<5; i++)
         {
        ;
         }
      var final_num='1';
      alert(final_num);
      }

which will simply alert 1.

You'd want to do something like:

function border(){
    var draftsToDisplay = <?php echo $var_drafts_display=0; ?>;
    for(var i=0; i<5; i++)
    {
        draftsToDisplay++;
    }
    alert(draftsToDisplay);
}

There is a great guide on the differences between client/server code, and some examples here.

Community
  • 1
  • 1
Blue
  • 22,608
  • 7
  • 62
  • 92
2

That kind of behavior is impossible. You need to clearly understand, how php and js works. PHP just compile web page html code on a server side and then it pass html code to a client. Client's web browser parsing that code and then execute all scripts. So your js machine will see the next code:

function border(){
      for(var i=0; i<5; i++)
         {
         }
      var final_num='1';
      alert(final_num);
      }
deniskoronets
  • 520
  • 3
  • 15
0

Are you displaying all iterations in individual alert box then you can do this:

function border(){
  <?php $var_drafts_display=0; ?>;
   var final_num = 0;
   for(var i=0; i<5; i++){
    <?php $var_drafts_display++ ; ?>;
    final_num='<?php  echo $var_drafts_display; ?>';
    alert(final_num);
  } 
}
charles okojie
  • 708
  • 2
  • 10
  • 23