Calling delete function on button with onclick

0

I want to press the DELETE button and delete X data from the database

this is my type_product.php

<?php require("header.php"); ?>
<?php require("menu.php"); ?>

<?php 
require ("model/tipo_itens.php");
$modTipoItens = new TipoItens();
$registros = $modTipoItens->getAll();

?>

    <div class="container">
         <center><h1>Categorias</h1></center>
         <button type="button" class="btn btn-success" onclick="window.location.href='tipo_produto_novo.php'">Nova Categoria</button>
         <table class="table table-striped"> 
            <thead> 
                <tr> 
                    <th>#</th> <th>Nome</th> <th>Descrição</th> 
                </tr>
            </thead> 
            <tbody>     
                <?php foreach ($registros as $registro) { ?>
                    <tr> 
                        <th scope="row"><?php echo $registro['id_tipo']; ?></th> <td><?php echo $registro['nome']; ?></td> <td><?php echo $registro['descricao']; ?></td> 
                        <td>
                            <button type="button" onclick="editar(<?php echo $registro['id_tipo']; ?>)" class="btn btn-primary">Editar</button>
                            <button type="button" onclick="delete(<?php echo $registro['id_tipo']; ?>" class="btn btn-danger">Apagar</button>
                        </td> 
                    </tr> 
                <?php } ?>                      
            </tbody> 
         </table>
    </div>

    <script type="text/javascript">
    function editar(id){
        window.location.href="tipo_produto_novo.php?id="+id;
    }
    </script>

<?php require("footer.php"); ?>

When I click the DELETE button, I want to delete the item selected by ID.

this is my controller tipo_itens.php

<?php
require ("../model/tipo_itens.php");
call_user_func($_GET['acao']);

function inserir(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->inserir($_POST);    
    header('Location: /exemplo/tipo_produto.php');
    exit;
}

function editar(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->editar($_POST); 
    header('Location: /exemplo/tipo_produto.php');
    exit;
}

function delete(){
    $modTipoItens = new TipoItens();
    $resultado = $modTipoItens->delete($_POST);
    header('Location: /exemplo/tipo_produto.php');
}

?>

and this is my delete function in model type_itens.php

   function delete($id){
      $conexao = mysqli_connect('localhost','root', '', 'estoque');
      $id = (int) $id;
      $result = mysqli_query($conexao,"delete from tipo_itens where id_tipo= ".$id);      
      return $result;
   }      

I'm not able to send the ID parameter when I click the button and execute the delete function of my model / tipo_itens.php

    
asked by anonymous 30.11.2017 / 18:47

1 answer

0

Let's break it down. There is a syntax error here:

<button type="button" onclick="delete(<?php echo $registro['id_tipo']; ?>" 
class="btn btn-danger">Apagar</button>

You have to close the parenthesis ( ) ) in delete(<?php echo $registro['id_tipo']; ?>) . Resolving this will still be a problem related to the use of the reserved word delete . This can be solved by changing the function name from delete() to, for example, remover() . So it looks like this:

<button type="button" onclick="remover(<?php echo $registro['id_tipo']; ?>)" 
class="btn btn-danger">Apagar</button>

Since you did not put the implementation of the remover() (old delete() ) function, I imagine it to be one of the problems as well. So to send the variable id passed to the remove function (using the http post method) it is necessary (more interesting) to use ajax . A native way of doing this in javascript is to use the api fetch . Applying to your case the implementation of the remove function, using api fetch, would look like this:

<script type="text/javascript">

    function remover(id){

    var formulario = new FormData();
    /*simula a existencia de um formulario, 
    onde o primeiro parametro é a chave (name) e o segundo o valor (value), 
    fazendo analogia com um campo input de um form*/

    formulario.append('id', id);

        fetch("/tipo_itens.php?acao=delete",
    {
        method: "POST",
        body: formulario
    })
    .then(function(resposta){ return resposta.text(); }).then(function(resposta){ 
   //faça algo com a resposta, por exemplo dizer "Salvo com sucesso!"
   alert(resposta); 

});         }     

In the code above, url /tipo_itens.php?acao=delete will access a file called type_itens.php present in the root directory of the server (change as needed), something like http://localhost/tipo_itens.php .

When doing the sequence of steps above the rest of your code should work properly. On the plus side, always use the browser debug (to see responses from ajax requests).

Finally a small example:

Arquivo layout.php:

<?php
$registro['id_tipo'] = 2;
?>

<button type="button" onclick="remover(<?php echo $registro['id_tipo']; ?>)" class="btn btn-danger">Apagar</button>

<script type="text/javascript">

function remover(id){

        var formulario = new FormData();
        formulario.append('id', id);

            fetch("/tipo_itens.php?acao=delete",
        {
            method: "POST",
            body: formulario
        })
        .then(function(resposta){ return resposta.text(); }).then(function(resposta){ 
    //faça algo com a resposta, por exemplo dizer "Salvo com sucesso!"
    alert(resposta); 
    });
}
</script>

File type_type.php:

<?php
if(isset($_POST['id'])){
    echo 'Operação realizada com sucesso! Recebido id ' . $_POST['id'] 
        . ' usando a ação ' . $_GET['acao'];
}
    
30.11.2017 / 20:10