Delete button crashes

Asked

Viewed 241 times

1

I have two buttons on my table, the edit and delete button:

<td><button type="button" name="edit" id="<?php echo $produto2["Id"]; ?>" data-target="#add_data_Modal2" class="btn btn-warning btn-sm edit_data2" ><span class="glyphicon glyphicon-pencil"></span></button></td>
<td><button type="button" id="<?php echo $produto2["Id"]; ?>" class="btn btn-dander btn-sm delete2" onsubmit="remove(this)"><span class="glyphicon glyphicon-trash"></span></button></td>

With the edit button I call the modal that has the save button, as shown in the code:

<button type="button" class="btn btn-success" onclick="inserir_registo2();">Gravar</button>

The problem is if you open the modal and close again without clicking the record button the delete button works correctly. But from the moment I open the modal to edit and click the record button, the delete button no longer works until you refresh the page.

I leave the insert function here:

function inserir_registo2()
{  

    var dadosajax = {
        'Id' : $("#Id2").val(),
        'DataTermino' : $("#DataTermino").val(),
        'Tratamento' : $("#Tratamento").val(),
        'Estado' : $("#Estado2").val(),
        'Prestador' : $("#Prestador").val()
    };
    $.ajax({
        url: './resolucaomanutencao',
        type: 'POST',
        cache: false,
        data: dadosajax,
        error: function(){
          $(".error_message").removeClass('hide');
        },
        success: function(result)
        { 
        $("#add_data_Modal2").modal("hide");
        $("#spoiler2").load(" #spoiler2 > *");
        }   
    });
}

delete function:

 remove = function(item) {

    var tr = $(item).closest('tr');

    tr.fadeOut(400, function() {
      tr.remove();  
    });

    return false;
  }

$(".delete2").click(function(){
        var id = this.id;
        if(confirm('Tem certeza de que deseja excluir a requisição?'))
        {
        $.ajax({ 
            url: "./deleterequisicao2", 
            type: "get",
            cache: false,           
            data: {id: id}, 
        error: function() {
                  alert('Algo está errado!');
               },
        success: function(data) {

                    $("#"+id).remove();
                    alert("Requisição removida com sucesso");
                    $("#spoiler2").load(" #spoiler2 > *");          
               }           
});

        }
});

Function of the edit button:

$(document).on('click', '.edit_data2', function(){  
           var employee_id2 = $(this).attr("Id");          
           $.ajax({  
                url:"./editarmanutencao",  
                method:"POST",
                cache: false,               
                data:{employee_id2:employee_id2},               
                dataType:"json",  
                success:function(data){

                    console.log(data);
                     $('#Id2').val(data.Id);
                     $('#Tratamento').val(data.Tratamento);
                     $('#Estado2').val(data.Estado);
                     $('#Prestador').val(data.Prestador);
                     $('#employee_id2').val(data.Id);                    
                     $('#insert2').val("Gravar");  
                     $("#add_data_Modal2").modal("show");                    
                }  
           });

      });  
  • And where is the function function remove(data) { ... } ?

  • @Ivan Ferrer already updated the question with the delete function

  • you are using modal: onsubmit, I think it is onclick, if you use onsubmit, will submit the form...

  • @Ivan Ferrer But if you put onclick, if you cancel, remove the row from the table and should not

  • instead of putting onclick or onsubmit, leave empty, and call the remove() method at the return of the $(".delete2")

  • The ids are folded both buttons in function inserir_registo2 receive id="${ item.Id }".

  • ... success: function(data) {&#xA; &#xA; var _self = $("#"+id);&#xA; &#xA; remove(_self); and remove it from the button: onsubmit="remove(this)"

  • In the question of ID folded, it is only concatenate né with a different string for each case... 'id_add_' + id and 'id_rm_'+ id

  • $("#id_rm_"+id).remove(); Duplicate ID will always fail.

  • @Ivan Ferrer did not understand the part of concatenating the folded ids. Where I apply this situation?

  • @Ivan Ferre even removing the code part of the two buttons inside the insert function_registo2 to avoid the folded ids, the delete button does not work after editing and saving a row in the table. I edited the question by removing this part of the code

  • What part don’t you understand about concatenating? You cannot have duplicated id, jquery does not find the element if you have duplicated id, you can take the value of your id and duplicate it since you concatene with a different string for each case, I gave an example for you to understand, you know that php will return an entire string right from your id, example: id="meuproduto_<?php echo $produto2["Id"]; ?>" will stay: id="meuproduto_1"... then you use this string as ID, of this string meuproduto_ is where you will vary.

  • @Ivan Ferrer, but after this id is different from the database id, it will not create problems when deleting or updating?

  • @Can Ivan Ferrer answer the code with the changes? I’m trying to apply everything suggested in the comments and I keep having the same problem, the button stops working.

  • I will try to give an answer, just to clarify what I am saying, but to make it work, I would need the full scope of your code.

  • @Sam we can talk on chat

Show 11 more comments

2 answers

6

1) Change your buttons:

Edit (which opens the modal):

<button type="button" name="edit" data-id="<?php echo $produto2["Id"]; ?>" id="open_<?php echo $produto2["Id"]; ?>" data-target="#add_data_Modal2" class="btn btn-warning btn-sm edit_data2" ><span class="glyphicon glyphicon-pencil"></span></button>

Delete:

<button type="button" data-id="<?php echo $produto2["Id"]; ?>" id="delete_<?php echo $produto2["Id"]; ?>" class="btn btn-dander btn-sm delete2"><span class="glyphicon glyphicon-trash"></span></button>

In his <tr> which is the container of the listed element, add:

data-itemid="<?php echo $produto2["Id"]; ?>"

2) in Javascript:

$(".delete2").click(function(){
        var id = $(this).data('id');
        $el = $("tr [data-itemid]");  
        if (confirm('Tem certeza de que deseja excluir a requisição?')) {
            $.ajax({ 
                url: "./deleterequisicao2", 
                type: "get",
                cache: false,           
                data: {id: id}, 
                error: function() {
                    alert('Algo está errado!');
                },
                success: function(data) {

                     $el.fadeOut(400, function() {
                         $el.remove();  
                         alert("Requisição removida com sucesso");
                         $("#spoiler2").load(" #spoiler2 > *");      
                     });

               }           
          });

       }
});
  • I figured out what the problem was and it was because of this line: $("#spoiler2").load(" #spoiler2 > *");, This is what makes the id repeat itself, how can I do the same without it happening?

  • 1

    Doing exactly as I said, use class instead of ID.

  • Although this is the solution, it could be improved by explaining the cause of the problem and then yes, offering the solution.

  • And what do you need to do this shipment for? $("#spoiler2").load(" #spoiler2 > *"); in your code is not specified.

1


When using AJAX, always use the delegated form of events.

Instead of using:

$(".delete2").click(function(){

Use:

$(document).on("click", ".delete2", function(){

The object document is always updated. Information about the method .on() you can find in the official documentation of jQuery -> https://api.jquery.com/on/

Browser other questions tagged

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