Change variable value after clicking PHP button

Asked

Viewed 3,013 times

2

Guys, I need you to $i change value to $i++ each click on the "Go".

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

<form method="post">

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

</form>

<?php

$i = 1;

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

    echo $i;

}

2 answers

2


So, friend, the way you want to do, using PHP, I don’t know if it’s possible, unless you pass an initial HTML value to PHP and make an ajax request for PHP to process this number, increment it in one and return to the view.

I don’t know what your purpose is and I don’t know if you really need to use PHP, but anyway I will post here a solution in javascript, it may be that give 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>

BS: I’m using jquery... stackoverflow won’t let you copy all the code, but I hope you understand...

  • 1

    It worked!!! Thanks boy! I believe that this way I will be able to implement in my original code! ;)

0

You can put a hidden field to keep control 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'];
}
  • I liked the solution! But I copied the code here and it didn’t work...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.