Remove record in database without giving refresh

Asked

Viewed 2,529 times

1

Buenas! I looked for some topics about the same doubt as mine - and I found, but I could not understand how to do... I have the following code snippet:

$c = array();
$c = buscaUsuario($conexao);

while($b = mysqli_fetch_assoc($c))
{?>
   <tr>
   <td><?php echo $b["user_name"]; ?></td>
   <td><?php echo $b["user_fullname"]?></td>
   <td><?php echo $b["user_email"]?></td>
   <td>
      <div class="btn-group">
        <a class="btn btn-primary" href="#"><i class="icon_plus_alt2"></i></a>
        <a class="btn btn-danger" onclick="deletarUsuario();"><i class="icon_close_alt2"></i></a>
      </div>
   </td>

And when you click the delete button it will call a js function called deletarUsuario(), where the id of that item will be passed. In this function, this is where I have to use Ajax, but I don’t know how to do it! I don’t know how to join the query of delete + javascript + ajax.

The reason I want to do this, is that by clicking the remove such item button, it removes without needing me to refresh the page.

This. With the $b variable I can recover the id, like this:

$b['id'];

As I have no idea how to use Ajax, I was doing it this way:

   <a class="btn btn-danger" href="procura-cadastro.php?id=<?php echo   $b['id'] ?>">

    <?php
       if(array_key_exists("id", $_GET) && $_GET['id'] == $b['id'])
       {
                $a = $_GET['id'];
                $b = deletaUsuario($conexao, $a);
       }

        }
             ?>
  • Which url to delete the user?

  • I forgot to add, sorry. I have a page called deleta-item.php and in it, is where I put the query that deletes some item.

  • It takes the id by parameter to be deleted deleta-item.php?id=1?

  • Laerte, I’m going to edit my question with the piece of code I put here to be better to view...

2 answers

1


You will do so:

$(".deletaUser").on('Click', deletarUsuario);

    function deletarUsuario(e){

        e.preventDefault();

        dados = {
            id : $(this).data('id')
        };

        $.ajax({
            url            : "deleta-item.php",
            type           : "POST",
            dataType       : 'JSON',
            data           : dados  
        }).done(function(data) {
          // aqui você faz alguma ação para quando o ajax retornar
        });
    }

<buttom class="deletaUser" data-id="<?php echo $b['id']; ?>">Deletar</buttom>

Then just get the $_POST['id'] in the archive deleta-item.php and run the query there

EDIT:

I changed the way I called the function, take the <a> who currently calls her and puts the button I mentioned there, there changes the JS also.

  • I made the implementation as you passed me, however when clicking the button nothing happens.

  • jquery is configured? for an error in the console? the path to the file deleta-item.php is correct (it’s great to put the entire path to the file "http://...")

  • Now that I saw it... In the console you are accusing that you do not find the file I created, ajax.js

  • test there and let me know something

  • To test, I put the function you passed me inside my html code (inside the proper tags is obvious) but in the console accuses that the deleting functionUsuario is not defined =/

  • I ran a test here and the function worked normal, I threw it in . js of a project that I’m working on now and I ran the function through Chrome’s console, she tried to find the file and sent the id, so far, js is perfect

  • "Referenceerror: deletarUsuario is not defined" :\

  • review to see if you’re really including the js at the end of the file, all right, because I’m sure it’s working

  • A very stupid question, but on the button I put: <a class="btn btn-Danger" onclick="deletarUsuario($b['id'])"></a> ?

  • this, you call the function in onclick, only fix pro php give an echo in $b['id'] within the function, will look like this: onclick="deletarUsuario(<?php echo $b['id']; ?>)" I missed there in the answer

  • Daniel, it worked! But it worked the same way I had done before without Ajax... I have to refresh the page to show that the item was deleted and I wanted to do without refresh...

  • I modified the answer, it was doing this because the navigated one was following the function of the button (you were using a <a> right?)

  • Referenceerror: $ is not defined... (for me jquery was included...)

  • the inclusion orders of the js are correct?

  • And what would be the inclusion orders? t-t

  • first includes jquery, then any other js

  • Jquery is already included by first...

Show 12 more comments

0

You can do it this way:

Add the jQuery library to the head of your document if you are not using it. You can download here .

On the tr of your table, put a unique id which will be used to hide tr after delete. Note that in the delete link I added a data-id which will be used in javascript to specify the user to be deleted and a class delete. If you want to use onclick you will have to pass the user id as parameter.

HTML

<tr id="tr_<?php echo $b["id"]; ?>">
   <td><?php echo $b["user_name"]; ?></td>
   <td><?php echo $b["user_fullname"]?></td>
   <td><?php echo $b["user_email"]?></td>
   <td>
      <div class="btn-group">
        <a class="btn btn-primary" href="#"><i class="icon_plus_alt2"></i></a>
        <a class="btn btn-danger deletar" data-id="<?php echo $b["id"]; ?>"><i class="icon_close_alt2"></i></a>
      </div>
   </td>

In the code that does the deletion process by PHP return [error => false] if the user is successfully deleted or ['error' => 'Mensagem informando alguma inconformidade'] that will be captured in the ajax Success.

JS

function deletarUsuario(id_usuario)
{
      $.ajax({
         url: 'sua url para excluir',
          type: 'post',
          data:{
           id: id_usuario
         },
         success: function(response)
         {
              if (!response.error) {

                $('#tr_'+id_usuario).fadeOut('slow');
              } else {
                alert(response.error);
              }
         },
         error: function(xhr)
         {
            alert(xhr.responseText);
         }
      });
}

$(function(){

    $(document).on('click','.deletar',function(){
        deletarUsuario($(this).data('id'));
        return false;
    });
});

Note that this was just a basic example of implementation. My code can be improved.

  • Hi Miguel, thanks for the answer. I implemented your code but it doesn’t make anything happen - of course for probably my mistake. In the console also nothing appears. It seems that the code of the function is not even running

  • @Cesara.Fonseca Do you upload the page via javascript or PHP? if you use it via javascript. you will have to change $('.deletar'). click to $(Document). on('click','.delete',Function(){}). check the Network + xhr option of the console to see if the ajax has been run

  • I think I’m gonna give up trying to learn and do this... no way. Your code and colleague Daniel’s run without error, but is not made the exclusion... And the query is correct, because before I could delete but the deletion only appeared when loading the page... I looked for tutorials on the internet but I could not understand anything of how to use Ajax... Feels like something out of this world :(

  • Never use that word give up. That’s not the option. If you want to learn more buy the book http://novatec.com.br/livros/ajaxjquery/ ajax with jquery

  • 1

    Hi Miguel... Thanks for the support man. I can’t and I will do everything not to give up. As much as Jquery, Ajax, seems like otherworldly things to me... I need to learn, I need to. Could you explain to me (or rather, give me links) explaining what some of your implementations do there? I opened the Ajax documentation but I could not understand much

  • I’ll put it in the answer

  • @Cesara.Fonseca in the answer I exemplified step by step for you to make the implementation. If you are in doubt in the language there is already another problem. I wish I could help. But now it depends on you.

Show 2 more comments

Browser other questions tagged

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