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 ie 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.
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 .
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);
}
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.