How to "activate" / "deactivate" a record using Ajax

1

After several attempts and searches I turn to you for the following problem. In a table I have a field in the DB that gives me the possibility to Activate or Not a record (for example, so that it can not be seen). I have a form to update high, but I need as that direct access and not bring all the data of the DB to update that single field. Since they can not have all the records the same ID is that I tried to do it with a function and passing the parameters to it. Use Bootstrap for the styles, hence if it is active, the "S" will be green or the "N" will be green. So far what I got is that by clicking on the respective button I change the "S" in the DB the "N" and vice versa, but I do not see the change of the letter or format without updating the page.

HTML

<table class="table table-condensed table-striped">
<tr>
    <th class="text-center" width="5px">Activo (S/N)</th>
    <th class="text-center" width="120px">Acción</th>
</tr>
<tr>
    <td class="text-center"><button onclick="modificar(18,'S')" class="btn btn-success btn-lg">S</button></td>
    <td class="text-center">
        <a class="btn btn-warning btn-lg glyphicon glyphicon-pencil" href="formAlertas.php?id=18" role="button" title="Editar"></a>
        <a class="btn btn-danger btn-lg glyphicon glyphicon-trash" href="borraAlertas.php?id=18" role="button" title="Eliminar" onclick="return confirm('¿Estas seguro?');"></a>
    </td>
</tr>
<tr>
    <td class="text-center"><button onclick="modificar(19,'N')" class="btn btn-success btn-lg">N</button></td>
    <td class="text-center">
        <a class="btn btn-warning btn-lg glyphicon glyphicon-pencil" href="formAlertas.php?id=19" role="button" title="Editar"></a>
        <a class="btn btn-danger btn-lg glyphicon glyphicon-trash" href="borraAlertas.php?id=19" role="button" title="Eliminar" onclick="return confirm('¿Estas seguro?');"></a>
    </td>
</tr>
</table>

PHP (active-alert.php)

<?php 

        $id = $_POST['id'];

        if( $_POST['activo'] === 'N' ) {
            $activo = 'S';
        } else {
            $activo = 'N';
        }
            $sql = "UPDATE 'tbl_alertas' SET 'activo'='$activo' WHERE 'id'='$id'";

            if (mysqli_query( $conn, $sql )) {
                    echo ("exitoso");
                } else {
                    echo ("invalido");
                }

            mysqli_close($conn);
?>

JQUERY

</table>
<script>
function modificar(idz,acti){
    var elem = $(this);
    var id = idz;
    var activo = acti;

    $.ajax({
        type: "POST",
        url: "activa-alerta.php",
        data: {id: id, activo:activo},
        success : function(text,elem){
            if (text == "exitoso"){
                alert(elem);
                esExitoso(elem);
                }
            else {
                esError();
            }
        }
    });

function esExitoso(elem){
   if ( activo === 'S' ) {
        alert(activo);
        elem.removeClass( "btn-danger" );
        elem.html('S');
        elem.addClass( "btn-success" );
    } else {
        alert(activo);
        elem.removeClass( " btn-success" );
        elem.html('N');
        elem.addClass( "btn-danger" );
        }   
    };
function esError(){
        alert('error');
    }; 
}

</script>
</body>
</html>

I think I do not forget anything. Thanks

    
asked by Soluciones PyMES y Hogares 22.01.2018 в 18:53
source

1 answer

2

I started to try the code and I saw that you were going to have problems to apply the changes.

I propose this solution. I try to briefly explain the essential changes:

In HTML

  • I changed the button elements in this way: <button id="btnSi" value="18" class="btn btn-success btn-lg">S</button> . As you can see, the function is not called from inside the button, passing the values to it. We have given a id to the button and we will use it in jQuery. That's because the other way could not easily recover the element with this and keep everything in the scope of the DOM was more complicated. Also, the 18 is now in the value tag, which you can easily recover in jQuery, as you will see later. And the S we already have in the text of the button ... The same goes for the other button.

Javascript / jQuery

  • We will use the code within $(function() { , it is the best practice, not to try to access the elements without the DOM being ready.

  • What was your old function modificar(idz,acti) , will be invoked here: $('#btnSi', '#btnNo').on('click', function() { . It will be a listener for the two buttons.

  • I have improved the Ajax code, using done and fail , since success is obsolete from jQuery 3.

  • Instead of calling the function esExitoso , we will treat everything within the done of Ajax. For simplicity, but if you want to call the function as you had before you can do it. I did not see much sense in doing it like that.

  • The function esError was also replaced, because it is better to handle errors with the fail , typical of the Ajax request.

I think that should work like that. If you have questions, you can comment.

I hope it serves you.

JS

$(function() {

  $('#btnSi, #btnNo').on('click', function() {
    var elem = $(this);
    var activo = elem.text();
    var id = elem.val();
    var url = 'activa-alerta.php';

    var request = $.ajax({
      data: {id: id, activo:activo},
      type: "POST",
      url: url,
      dataType: "html"
    });

    request.done(function(text) {
      console.log(text);
      if (text == "exitoso") {
        if (activo == 'S') {
          elem.removeClass('btn-danger').addClass('btn-success');
          elem.text('S');
        } else {
          elem.removeClass('btn-success').addClass('btn-danger');
          elem.text('N');
        }
      }
    });

    request.fail(function(jqXHR, textStatus) {
      alert("Error de petición: " + textStatus);
    });

  });

});

HTML

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed table-striped">
  <tr>
    <th class="text-center" width="5px">Activo (S/N)</th>
    <th class="text-center" width="120px">Acción</th>
  </tr>
  <tr>
    <td class="text-center"><button id="btnSi" value="18" class="btn btn-success btn-lg">S</button></td>
    <td class="text-center">
      <a class="btn btn-warning btn-lg glyphicon glyphicon-pencil" href="formAlertas.php?id=18" role="button" title="Editar"></a>
      <a class="btn btn-danger btn-lg glyphicon glyphicon-trash" href="borraAlertas.php?id=18" role="button" title="Eliminar" onclick="return confirm('¿Estas seguro?');"></a>
    </td>
  </tr>
  <tr>
    <td class="text-center"><button id="btnNo" value="19" class="btn btn-success btn-lg">N</button></td>
    <td class="text-center">
      <a class="btn btn-warning btn-lg glyphicon glyphicon-pencil" href="formAlertas.php?id=19" role="button" title="Editar"></a>
      <a class="btn btn-danger btn-lg glyphicon glyphicon-trash" href="borraAlertas.php?id=19" role="button" title="Eliminar" onclick="return confirm('¿Estas seguro?');"></a>
    </td>
  </tr>
</table>
    
answered by 23.01.2018 / 00:13
source