Decrease PHP variable when clicking on a form button

3

I want to decrement a numeric variable when I load a button named btn .

This is the code I tried:

$month = date("m");

$mes=1;
if(isset($_POST["btn"])) { 

    $month = $month-$mes;
    $mes++;

}

The problem is that I always get the same value.

    
asked by anonymous 27.11.2014 / 22:53

2 answers

5

The problem is that you are zeroing the values for every PHP call.

Here's a very simplified example of how to persist data between clicks:

<?php
   if( isset( $_POST['mes'] ) ) {
      $mes = 0 + $_POST['mes'];
   } else {
      $mes = 0 + date('m');
   }

   if( @$_POST['btn'] == '-' ) { 
      $mes--;
   } else if( @$_POST['btn'] == '+' ) {
      $mes++;
   }

   echo "Mes: $mes<br>";
   echo '<form method="post">';
   echo '<input type="submit" name="btn" value="-">';
   echo '<input type="submit" name="btn" value="+">';
   echo '<input type="hidden" name="mes" value="'.$mes.'">';
   echo '</form>';
?>


And before anyone complains, deletion in PHP is for that very reason. It's to use where there's no problem. ISSET in such a case does not make sense.

    
27.11.2014 / 23:34
0

This function can be done in javascript also if necessary, and only send the month that has been configured. I'll give you an example.

$("#btnEnviar").on("click" , function(){
  $.ajax({
    url : 'caminhodoarquivo.php' ,
    type : 'POST' ,
    dataType : 'json' ,
    data : { 
      mes : $("#txtMes").val()
    },
    sucess : function(resultado){
      //Faz o retorno para a o usuário
    },
    error : function( jqXHR, textStatus, errorThrown ){
      console.error(textStatus);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!--LatestcompiledandminifiedCSS--><linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script><formaction="#" method="POST" id="frmMes" class="form">
  <input type="number" id="txtMes" min="1" max="12" />
  <button type="submit" id="btnEnviar" class="btb btn-primary">
    <span>Enviar</span>
  </button>
 </form>

Comments: Using the number element (input type number) and the min and max properties, you avoid silly errors such as month 14 or -1.

I hope I have helped,

Douglas Dreer

    
28.11.2014 / 12:48