Jump to content

global variable counter


jwrightnisha

Recommended Posts

Hello, I am  trying to increment a php variable by clicking on a button.

I've tried placing the variable in various spots and experimented with global and static keywords but I just can't get the variable to increment.

Any help would be greatly appreciated. Cheers, James

 

<html>

<head>

<title>Increment</title>

<?php static $i = 0; ?>

</head>

<body>

<?php

function incrementI()

{

$i++;

return $i++;

}

?>

<SCRIPT language="JavaScript">

<!--

function f1()

{

var val = "<?php echo incrementI(); ?>";

var message = "The value of i now is " + val;

alert(message)

}

//-->

</SCRIPT>

<input name="btnNext" type="button" id="btnNext" onClick="f1(); " value="Next">

</body>

</html>

Link to comment
Share on other sites

A web page in a browser cannot directly "call" php code on the server. A browser can only make http/https requests to the web server.

 

Your button/link would either need to request the URL of a page that contains php code to increment the value or you can use AJAX to make the http request to the page.

 

You will also need to store the variable that is being incremented in a session (or a database) because all the resources that a .php page uses are destroyed when the code on that page reaches the end of the page. Static variables in functions are only static for the page they are on. They don't persist between page visits or page refreshes.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.