Calling delete function in the button with onclick



  • I want to press the APAGAR button and delete X database data

    that's my product type. php

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

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

    ?>

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

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

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

    this is my controller type_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 the model_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;
    }

    Do not be able to send the ID parameter when I click on the button and perform the delete function of my model/type_itens.php



  • Let's go for parts. There is a syntax error here:

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

    For it is necessary to close the kinesis ()) in delete(<?php echo $registro['id_tipo']; ?>). Resolving this will still be a problem related to the use of the reserved word https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords . This can be solved by changing the function name delete() for, for example, remover(). So it's 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() (Old delete()), I imagine it is also one of the problems. So, to send the passed variable id to the remove function (using the post method of the http) it is necessary (more interesting) to use https://developer.mozilla.org/pt-BR/docs/Web/Guide/AJAX . A native way to do this in javascript is by using api https://developer.mozilla.org/pt-BR/docs/Web/API/Fetch_API/Using_Fetch . Applying to your case the implentation 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 above code, the url /tipo_itens.php?acao=delete accessed a file called type_itens.php present in the server root directory (change as needed), something like http://localhost/tipo_itens.php.

    When sequencing steps above the rest of your code should work properly. In addition, always use the browser debug (to see the ajax requests responses).

    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_itens. php:

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




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2