John Davidson

how to update a php global variable in javascript?

0 comments
Message:


I want to update the PHP global counter on click of a button in Javascript. The reason I'm using PHP global variable instead of JavaScript global variable is that initially the records come from database which can be done using of course only PHP. Below is the code for that


       $('#AddOpponent').click(function(){
<?php $GLOBALS['counter']=$GLOBALS['counter']+1; ?>
var c=<?php echo $GLOBALS['counter'];?>
//c=c+1;
var str="<br> <br> <p>Opponent No " + c +"</p> <select id=\"opponent_id" + c +"\" name=\"opponent_id" + c +"\" class=\"form-control input sm select2\">" + options +"</select>";
$( "#AppendForm" ).append(str);
$("#Oppcounter").val(c);
//alert(str);


});

EDIT: Instead of incrementing the PHP global variable, copying it's value to a js variable and then incrementing on button click. Apparently showing the same result as '3' on every button click


        $('#AddOpponent').click(function(){
c=<?php echo $GLOBALS['counter'];?>
c=c+1;
var str="<br> <br> <p>Opponent No " + c +"</p> <select id=\"opponent_id" + c +"\" name=\"opponent_id" + c +"\" class=\"form-control input sm select2\">" + options +"</select>";
$( "#AppendForm" ).append(str);
$("#Oppcounter").val(c);
//alert(str);
});

but it updates just once . For example if the current counter is 2, on every click of the button the counter shows as just 3 always
PS: There are no errors in the console


Thanks



My Answer:
It seems like the issue is with the way you are updating the counter variable in JavaScript. Instead of incrementing the PHP global variable directly in JavaScript, you should copy its value to a JavaScript variable and then increment that variable on button click.

Here is the updated code:

javascript
$('#AddOpponent').click(function(){
var c = ;
c = c + 1;
var str = "

Opponent No " + c + "

";
$("#AppendForm").append(str);
$("#Oppcounter").val(c);
});


By copying the value of the PHP global variable to a JavaScript variable and then incrementing that variable on button click, you should see the counter increment correctly with each click.

Rate this post

4 of 5 based on 4222 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us