Change value of variable after click button in PHP

2

Well, I need the $i to change value to $i++ with each click on the "Go" button.

That is, I click the button and "1" will appear, when I click again "2" will appear, and so on. How can I do it?

<form method="post">

    <input type="submit" name="Submit" value="Go!">

</form>

<?php

$i = 1;

if (isset($_POST["Submit"])){

    echo $i;

}
    
asked by anonymous 16.08.2015 / 16:52

2 answers

2
So, friend, the way you want to do it using PHP, I do not know if it is possible, unless you pass an initial value from HTML to PHP and make an ajax request for PHP to process this number, increment in one and go back to the view.

I do not know what your purpose is and I do not know if you really need to use PHP, but anyway I'll post a solution here in javascript, it might give you the result you want ...

<html>

              

<form id = "formulario">
    <input type = "submit" name = "Submit" value = "Go!">
    <label id = "resultado">1</label>
</form>

<script type="text/javascript">
    var i = 1;
    $("#formulario").submit(function(e) {
        e.preventDefault();
        i++;
        $("#resultado").html(i);
    });
</script>

I'm using jquery ... stackoverflow does not let you copy all the code, but I hope you understand ...

    
16.08.2015 / 17:39
0

You can put a hidden field to keep track of the counter and increment it by PHP every POST submission.

<form method="post">
    <input type="hidden" name="contador" value="<?php echo isset($_POST['contador']) ? $_POST['contador'] : 1; ?>">
    <input type="submit" name="Submit" value="Go!">
</form>

if (isset($_POST["Submit"])){
    $_POST['contador']+=1;
    echo $_POST['contador'];
}
    
16.08.2015 / 17:18