Calling delete function on onclick button

Asked

Viewed 1,887 times

0

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

this is my product type.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 the ID.

this is my entry type controller.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 the item type model.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 am unable to send the ID parameter when I click on the button and execute the delete function of my model/item type.php

  • Try it this way: <button type="button" onclick="edit('<?php echo $record['id_type']; ?>')" class="btn btn-Primary">Edit</button> <button type="button" onclick="delete('<?php echo $record['id_type']; ?>')" class="btn btn-Danger">Delete</button> Indicate which error appears if not.

1 answer

1

Let’s split. There’s a syntax error here:

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

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

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

How you did not put the implementation of the function remover() (ancient delete()), I imagine that’s one of the problems as well. Then, to send the id variable passed to the remove function (using http post method) it is necessary (more interesting) to use ajax. A native way to do this in javascript is by using the api fetch. Applying to your case the implentation of the remove function, using the fetch api, 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 above code, the url /tipo_itens.php?acao=delete access a file called type_items.php present in the server root directory (change as needed), something like http://localhost/tipo_itens.php.

When doing the above step sequence the rest of your code should work properly. Also, always use the browser debug (to see responses to 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_items.php:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.