Delete button with mysql / php modal

0

I'm a beginner and I'm having a problem with a button (delete with modal). When clicking the button, the system should display the modal and if I click "yes", you should delete the registry.

I'm keeping my codes on a single page: "details.php".

Button code:

<form method="post" action="">
    <div class="direita" style="padding-right:30px;">
    <a href="#excluir" data-uk-modal >
    <div class="btn_all2" type="submit" id='btnApagar' style="margin-left:15px; background-color:#ff0000;">
                EXCLUIR </div> </a>
</form>

Mod code:

<div id="excluir" class="uk-modal" >
<div class="uk-modal-dialog">
    <div class="uk-modal-header">Excluir</div>
    Deseja mesmo excluir a tarefa?
    <div class="uk-modal-footer uk-text-right">
        <a class="uk-button" href="">Não</a>
        <a class="uk-button uk-button-primary" type="submit" name="botaoConfirma" value="true" href="painel_constru.php?constru=tarefas">Sim</a>
    </div>
</div>

Button triggered condition:

$codigo=$_GET["id"];
if (isset($_POST["btnApagar"])) {

    if (isset($_POST["botaoConfirmar"])) {
        $comandoExcluir = "DELETE FROM tbTarefa WHERE idTarefa =" .$codigo; 
        $resultado = $c ->criarConsulta($comandoExcluir);

        if ($resultado) {
            echo "Removido com sucesso";
        } else{
            echo "Não foi removido";
        }
    }
}

Clicking the button does not delete the record. I was seeing that this can be done in ajax, but I do not have much practice yet and I would also like to know if it is possible to make it work that way. Thanks in advance.

Method of creating the query:

public function criarConsulta ($sql)
{
     $this->conectarBd();
     $this->comandoSql = $sql; 
     // $result= mysqli_query($con,$comandoSql);
     if ($this->result =mysqli_query($this->con,$this->comandoSql)) {
         $this->desconectarBd();
         return $this->result;
     } else {
       echo "Nao foi possivel realizar comando sql";
       die();
       $this->desconectarBd();
     }
} 
    
asked by anonymous 03.11.2016 / 12:47

1 answer

2

Using modal, you should think of front-end first, the back-end part should be thought of later:

HTML:

<div id="status" class="alert"></div>
<table class="table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Título</th>
            <th>Detalhes</th>
            <th>Status</th>
            <th>Ação</th>
        </tr>
    </thead>
    <!-- start: Table Body -->
    <tbody>
        <tr class="btnDelete" data-id="1">
            <td>1</td>
            <td><a href="#">Título x</a></td>
            <td>Blá blá blá</td>
            <td>Ativo</td>
            <td>
                <button class="btn btn-danger btnDelete" href="">Apagar</button>
            </td>
        </tr>
        <tr class="btnDelete" data-id="2">
            <td>2</td>
            <td><a href="#">Título y</a></td>
            <td>Blá blá blá</td>
            <td>Ativo</td>
            <td>
                <button class="btn btn-danger btnDelete" href="">Apagar</button>
            </td>
        </tr>
    </tbody>
</table>
<!--/table-collapse -->
<!-- start: Delete Coupon Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h3 class="modal-title" id="myModalLabel">Exclusão de registro</h3>

            </div>
            <div class="modal-body">
                 <h4> Você gostaria de deletar este item?</h4>

            </div>
            <!--/modal-body-collapse -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="btnDelteYes" href="#">Sim</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Não</button>
            </div>
            <!--/modal-footer-collapse -->
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->

Javascript:

$('button.btnDelete').on('click', function (e) {
    e.preventDefault();
    var id = $(this).closest('tr').data('id');
   //aqui passamos a ID do registro para dentro do modal, atraveś do click do botão...
    $('#myModal').data('id', id).modal('show');
});

$('#btnDelteYes').click(function () {
    var id = $('#myModal').data('id');
    $('[data-id=' + id + ']').remove();
    $('#myModal').modal('hide');
});

Here's an example in JSFIDDLE .

Now we move the action to the backend, so that the exclusion is met in PHP. First we change the method so that it allows to make a post via ajax:

$(function() {
  $('#status').hide();
});
$('#btnDelteYes').click(function () {
    var id = $('#myModal').data('id');
    $.post('detalhesTarefas.php',{acao:'delete',id:id},function(r) { 
       var m = jQuery.parseJSON(r);
       if (m.success) {
        $('[data-id=' + id + ']').remove();
        $('#myModal').modal('hide');
        $('#status').removeClass('alert-danger')
                    .addClass('alert-success')
                    .text(m.msg).fadeIn('slow');
       } else {
        $('#myModal').modal('hide');
        $('#status').removeClass('alert-success')
                    .addClass('alert-danger')
                    .text(m.msg).fadeIn('slow');
       }
          hideMessage();
    }
});

function hideMessage() {
    setTimeout(function() {
        $('#status').hide();
    }, 4000);
}

In php, since you are using everything in a single file, it is important that this code be placed at the beginning of it and that the file does not contain html code next to its output, since JSON should be your only answer output, so this will use die () , to interrupt any execution that comes below this action, so that it understands that only in this condition it should be attended to, I put a POST entry called "action" say to the back end, in which part of your file it will answer the response. Your php file should look like this:

<?php //primeira linha do arquivo php
if ($_POST) {
    $data = array('success' => '0',
                  'msg' => 'Ocorreu um erro, nada foi excluído!');
        $id = (int) $_POST['id'];
        if ($_POST['acao'] == 'delete' && is_int($id)) {
            $comandoExcluir = "DELETE FROM tbTarefa WHERE idTarefa =" .$id; 
            $resultado = $c ->criarConsulta($comandoExcluir);
            if ($resultado) {
               $data = array('success' => '1',
                             'msg' => 'Registro excluído com sucesso!');
            } 
        }
   echo json_encode($data);
   die();
}
//aqui abaixo virá o resto do seu código, html etc....
?>
    
03.11.2016 / 14:24