Ajax - PHP - Error status change button

2

I have a table where I show users with a column / id of "state". Where you will have two values: color green (activo, estado=1) or color red (inactivo, estado=0) . I have the following code to change the state but it shows me the initial green color but it does not change me when I click on the button.

Where do I have the error?

index.php

<table class="table table-striped" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt"> <!-- table-hover === se selecciona la fila indicada con el raton -->
                    <center>
                    <!-- Indicamos el nombre de las columnas de la tabla a visualizar. -->
                    <!-- TABLE = crear una tabla        TR = crear una fila        TD = crear una columna -->
                    <tr>
                        <thead style="background-color:#A9F5A9">
                        <td>
                            <font face="verdana" color="blue"><b><center>ID</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Login</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Email</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Nombre</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Apellidos</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Ciudad</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Teléfono</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Fecha registro</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Estado</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Modificar</center></b></font>
                        </td>
                        <td>
                            <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                        </td>
                        </center>
                        </thead>
                    </tr>

                    </center>
                    <?php
                        //Extraemos la informacion de ambas tablas relacionadas con el foreign key (ID_OBLIGATORIO).
                        $query = "SELECT * FROM usuarios_obligatorios JOIN usuarios_datos ON usuarios_obligatorios.ID_OBLIGATORIO = usuarios_datos.ID_OBLIGATORIO ORDER BY usuarios_obligatorios.ID_OBLIGATORIO ASC";
                        $result = mysql_query($query);
                        $numero = 0;
                        //Mientras existen datos, los agregamos en la tabla (mediante filas).
                        while($row = mysql_fetch_array($result)){
                            echo "<tr>";
                                echo "<td width=\"05%\"><font face=\"verdana\"><font size='2'>".$row["ID_OBLIGATORIO"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["login"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["email"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["nombre"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["apellidos"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["ciudad"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["telefono"]."</font></font></td>";
                                echo "<td width=\"10%\"><font face=\"verdana\"><font size='2'>".$row["fecha_registro"]."</font></font></td>";

                                echo "<td width=\"08%\">" ?>
                                    <!-- Columna ESTADO del usuario. (estado verde/rojo). -->
                                    <center>
                                        <?php
                                            $estado = 1;
                                            $class = "activo";
                                        ?>
                                        <button class="activar <?php echo $class;?>" data-estado="<?php echo $estado?>" style="height: 14px; width:14px;"></button>
                                    </center>
                                <?php 
                                echo "</td>";   

                                echo "<td width=\"08%\">" ?>    
                                    <!-- Columna MODIFICAR usuarios. Nos redirige a modificar.php (formulario ya con los datos cargados) gracias a: <a href="modificar.php?Id=<?=$row["ID_OBLIGATORIO"]?>"> 
                                         Al pasar el raton encima de cada modificar, abajo en el navegador podemos ver el valor de cada ID: osmar.fyb3/modificar.php?Id=7 -->
                                    <center><a href="modificar.php?Id=<?=$row["ID_OBLIGATORIO"]?>"><img src="imagenes/modificar.png" height='24' width='26' onmouseover="this.src='imagenes/modificar_in.png';" onmouseout="this.src='imagenes/modificar.png';"></center> <?php echo "</td>";
                                echo "<td width=\"08%\">" ?> 
                                    <!-- Columna ELIMINAR usuarios (checkbox). Sabemos el valor de cada fila mediante: value="<?php echo $row['ID_OBLIGATORIO']; ?>" 
                                         Al dar en el boton ELIMINAR_SELECCIONADOS, los borraremos. Guardamos los marcados en un array llamado seleccionados[] cuyo
                                         valor lo extraemos mediante: value="<?php echo $row['ID_OBLIGATORIO']; ?>" 
                                    -->
                                    <center><img src="imagenes/eliminar.png" height='23' width='24' alt="Eliminar">&nbsp;&nbsp;<input type="checkbox" name="seleccionados[]" id="seleccionados" value="<? echo $row['ID_OBLIGATORIO']; ?>">
                                    </center> <?php echo "</td>";
                            echo "</tr>"; 
                            $numero++;
                        }
                        mysql_free_result($result);
                    ?>
                </table>

                <!-- Boton ELIMINAR SELECCIONADOS -->
                <div class="boton_eliminar" class="table-responsive" align="right">
                    <font face="verdana">
                    <b><input type="submit" style="width:200px; height:28px;" name="eliminar_seleccionados" id="eliminar_seleccionados" onclick="return confirm('¿Deseas realmente eliminar estos usuarios?');" value="Eliminar seleccionados"></b></font><br/><br/>
                </div>
                <?php
                    //Si no existen datos ($filas == 0), icono de la BBDD vacia.
                    }else{
                ?><br/><h1><b><font size="16"><center>BASE DE DATOS SIN DATOS</center></font></b></h1><br/><center><img src="imagenes/bbdd.png" height="180" width="160"/></center>
                <?php
                    }
                ?>
            </div>
        </div>
        </form>
        <?php
            //Aqui va el codigo del boton eliminar_seleccionados...
            //Si pulsamos el boton "Eliminar seleccinados"... 
            if(isset($_POST['eliminar_seleccionados'])) {
                if(empty($_POST['seleccionados'])) {
                    echo "<center><h2>No se ha seleccionado ningun usuario.</center></h2>";
                }else{
                    foreach($_POST['seleccionados'] as $valor){
                        $res1 = mysql_query("DELETE FROM usuarios_obligatorios WHERE ID_OBLIGATORIO=".$valor."");
                        $res2 = mysql_query("DELETE FROM usuarios_datos WHERE ID_OBLIGATORIO=".$valor."");
                        $res3 = mysql_query("DELETE FROM usuarios_aficiones WHERE ID_OBLIGATORIO=".$valor."");
                    }
                    echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
                }
            }
        ?>
    </body>
</html>




<script>
    //Funcion al clickear el button del ESTADO.
    $('.activar').click(function(){
        //Recogemos el valor de la variable "data-estado".
        var estado = $('.activar').attr('data-estado'); 
        //Llamamos al cambiar_estado.php y le pasamos el valor a la funcion.
        $.post('cambiar_estado.php', {estado:estado}, function(response){
            //Dato = responde = 0, entonces desactivamos (color rojo). 
            if(response == 0){
                $('.activar').removeClass("activo");
                $('.activar').addClass("inactivo");
            }else{
                $('.activar').removeClass("inactivo");
                $('.activar').addClass("activo");
            }
        //Retornamos de nuevo el dato.
        $('.activar').attr('data-estado', response); 
        });
    });
</script>

index.js

$('.activar').on('click', cambiarEstado);

function cambiarEstado () {
  var estado = $(this).attr('data-estado');
  $.post('cambiar_estado.php', {estado:estado});
}

change_state.php

<?php
  $estado = $_POST['estado'];
  if ($estado == '1'){
    $dato = 0;
  }
  else{
    $dato = 1;
  }

?>
    
asked by omaza1990 14.11.2016 в 11:44
source

2 answers

2

Well, the first thing you would do would be to avoid putting those names in your css classes and also add . since that is the correct way to define a class.

.inactivo{
   background-color: red;
}
.activo{
   background-color: green;
}

Second, your code php does not return anything, you should add:

<?php
  $estado = $_POST['estado'];
  if ($estado == 1){
    $dato = 0;
  }
  else{
    $dato = 1;
  }
  echo $dato;
?>

Third, after receiving the data, you should change the class which has your button.

<?php
  $estado = 1;
  $class = "activo";
?>
<button class="activar <?php echo $class;?>" data-estado="<?php echo $estado?>">Cambiar estado</button>


<script>
$('.activar').click(function(){
    var estado = $('.activar').attr('data-estado'); 
    $.post('cambiar_estado.php', {estado:estado}, function(response){
        if(response == 0){
            $('.activar').removeClass("activo");
            $('.activar').addClass("inactivo");
        }else{
            $('.activar').removeClass("inactivo");
            $('.activar').addClass("activo");
        }
    $('.activar').attr('data-estado', response); 
    });
});
</script>

EDITING

Since you changed your question, do not use all your code but I made an example that changes the state of the corresponding button.

<table>
    <tr>
        <thead>
            <td>
                Id
            </td>
            <td>
                Boton
            </td>   
        </thead>
    </tr>
    <?php
        for ($i = 1; $i <= 3; $i++) {
            echo "<tr>";
            echo "<td class='id' data-id='$i'>$i</td>";
            $estado = 1;
            $clase = "activo"; 
    ?>
            <td><button class="activar <?php echo $class;?>" data-estado="<?php echo $estado ?>">Boton</button></td>
    <?php
        echo "</tr>";
        }
    ?>
</table>

And the script was:

<script>
$('.activar').click(function(){
    var row = $(this).closest("tr");
    var estado = row.find(".activar").attr('data-estado'); 
    alert(row.find(".id").attr('data-id'));
    console.log("estado "+estado)  
    $.post('cambiar_estado.php', {estado:estado}, function(response){
    estado = response;
    console.log(estado);
        if(response == 0){
            row.removeClass("activo");
            row.addClass("inactivo");
        }else{
            row.removeClass("inactivo");
            row.addClass("activo");
        }
        row.find(".activar").attr('data-estado', estado); 
    });  
});
</script>

By clicking on the button in the row of the table, I get that row. Then I get the class "activate" of that particular row (which is your button) and there I get data, I send it and I modify it.

When you get var row = $(this).closest("tr"); you get the <tr> complete, so you can access their <td> . Ideally, each field of your users had a class for example in this case class="id" , with this you can search within your <tr> the <td> that has that class or another. And finally you accede to its attribute.

    
answered by 14.11.2016 в 13:13
1

There are several causes why the code may not be working:

  • In the css a point ( . ) is missing to indicate class. Both button 1 and button 1.

  • In the AJAX call (the $.post ), you are not doing anything to read the result or change the status of the button when the result of changing_state.php is received.

    You would need to add a third parameter that would be the function to execute when a result is received. And that would change the button class depending on the value obtained.

  • In change_estado.php you are performing operations but you do not return your result, so the JavaScript does not receive anything back.

    You would miss something like echo $dato; .

  • From the information and the new code that you have added to the question:

    //Funcion al clickear el button del ESTADO.
    $('.activar').click(function(){
        //Recogemos el valor de la variable "data-estado".
        var estado = $('.activar').attr('data-estado'); 
        //Llamamos al cambiar_estado.php y le pasamos el valor a la funcion.
        $.post('cambiar_estado.php', {estado:estado}, function(response){
            //Dato = responde = 0, entonces desactivamos (color rojo). 
            if(response == 0){
                $('.activar').removeClass("activo");
                $('.activar').addClass("inactivo");
            }else{
                $('.activar').removeClass("inactivo");
                $('.activar').addClass("activo");
            }
        //Retornamos de nuevo el dato.
        $('.activar').attr('data-estado', response); 
        });
    });
    

    The problem you have now is that in the function that controls the result of $.post you are using the class ".activate" that appears in numerous elements and not only in the one that has been pressed.

    Try to change it so that instead of all the elements with class "activate" are the objectives, it is exclusively the one that was clicked:

    //Funcion al clickear el button del ESTADO.
    $('.activar').click(function(){
    
        // guardamos el elemento que se ha pulsado
        var $this = $(this);
    
        //Recogemos el valor de la variable "data-estado".
        var estado = $this.attr('data-estado'); 
        //Llamamos al cambiar_estado.php y le pasamos el valor a la funcion.
        $.post('cambiar_estado.php', {estado:estado}, function(response){
            //Dato = responde = 0, entonces desactivamos (color rojo). 
            if(response == 0){
                $this.removeClass("activo");
                $this.addClass("inactivo");
            }else{
                $this.removeClass("inactivo");
                $this.addClass("activo");
            }
    
            //Retornamos de nuevo el dato.
            $this.attr('data-estado', response); 
        });
    });
    
        
    answered by 14.11.2016 в 13:09