Jump to content

Como corrigir problema ao capturar 'item.id' em JavaScript com jQuery?


Junior Setti

Postagens Recomendadas

Ola pessoal, estou com uma duvida, se alguem puder me ajudar: 

 

<script type="text/javascript">

    $(document).ready(function() {

        // Exibir itens ao clicar no botão 'Detalhes'

        $('.detalhes-btn').on('click', function(e) {

            e.preventDefault();

            var produtoId = $(this).data('produto-id');

 

            $.ajax({

                url: '{% url "get_itens_receita" 0 %}'.replace('0', produtoId),

                type: 'GET',

                success: function(response) {

                    var itensTable = $('#itens_receita tbody');

                    itensTable.empty();

                    $.each(response.itens, function(index, item) {

                        var newRow = $('<tr>');

                        newRow.append('<td>' + (index + 1) + '</td>');

                        newRow.append('<td>' + item.ingrediente + '</td>');

                        newRow.append('<td class="text-center">' + item.quantidade + ' ' + item.medida + '</td>');

                        newRow.append('<td class="text-center">R$ ' + parseFloat(item.preco_custo).toFixed(2) + '</td>');

                       newRow.append('<td class="text-center"><button class="btn btn-danger excluir-btn" data-item-id="' + item.id + '">Excluir</button></td>');                        

                        itensTable.append(newRow);

                    });               

                 

        // Excluir item ao clicar no botão 'Excluir'

        $(document).on('click', '.excluir-btn', function(e) {

            e.preventDefault();

            var itemId = $(this).data('item-id');

 

            if (typeof itemId === 'undefined') {

                console.error('item-id is undefined');

                return;

            }

 

            $.ajax({

                url: '{% url "excluir_item_receita" %}',

                type: 'POST',

                data: {

                    'item_id': itemId,

                    'csrfmiddlewaretoken': '{{ csrf_token }}'

                },

                success: function(response) {

                    if (response.success) {

                        // Remove a linha da tabela

                        var row = $('.excluir-btn[data-item-id="' + itemId + '"]').closest('tr');

                        row.remove();

                    } else {

                        console.error('Erro ao excluir o item:', response.error);

                    }

                },

                error: function(xhr, status, error) {

                    console.error('Erro ao excluir o item:', error);

                }

            });

        });

    });

</script>

Não estou conseguindo pegar o "item.id" (linha amarela) e atribuir a variavel var itemId = $(this).data('item-id'); (linha verde)

  • Curtir 1
Link to comment
Compartilhe em outros sites

Fala, @Junior Setti!

 

O problema que você está enfrentando provavelmente está relacionado ao escopo e ao carregamento do manipulador de eventos para o botão "Excluir". Quando você anexa o manipulador de eventos .on('click', ...) diretamente dentro da função de sucesso do AJAX, o manipulador de eventos pode não estar acessível fora desse escopo ou pode não ser anexado corretamente aos novos elementos dinâmicos.

Uma solução comum é garantir que o manipulador de eventos para o botão "Excluir" seja anexado corretamente após os elementos serem inseridos na página. Outra solução é mover o manipulador de eventos para fora da função de sucesso do AJAX e usar o delegador de eventos do jQuery.

 

<script type="text/javascript">
$(document).ready(function() {
    // Exibir itens ao clicar no botão 'Detalhes'
    $('.detalhes-btn').on('click', function(e) {
        e.preventDefault();
        var produtoId = $(this).data('produto-id');

        $.ajax({
            url: '{% url "get_itens_receita" 0 %}'.replace('0', produtoId),
            type: 'GET',
            success: function(response) {
                var itensTable = $('#itens_receita tbody');
                itensTable.empty();
                $.each(response.itens, function(index, item) {
                    var newRow = $('<tr>');
                    newRow.append('<td>' + (index + 1) + '</td>');
                    newRow.append('<td>' + item.ingrediente + '</td>');
                    newRow.append('<td class="text-center">' + item.quantidade + ' ' + item.medida + '</td>');
                    newRow.append('<td class="text-center">R$ ' + parseFloat(item.preco_custo).toFixed(2) + '</td>');
                    newRow.append('<td class="text-center"><button class="btn btn-danger excluir-btn" data-item-id="' + item.id + '">Excluir</button></td>');                        
                    itensTable.append(newRow);
                });
            },
            error: function(xhr, status, error) {
                console.error('Erro ao carregar os itens:', error);
            }
        });
    });

    // Excluir item ao clicar no botão 'Excluir'
    $(document).on('click', '.excluir-btn', function(e) {
        e.preventDefault();
        var itemId = $(this).data('item-id');

        if (typeof itemId === 'undefined') {
            console.error('item-id is undefined');
            return;
        }

        $.ajax({
            url: '{% url "excluir_item_receita" %}',
            type: 'POST',
            data: {
                'item_id': itemId,
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            success: function(response) {
                if (response.success) {
                    // Remove a linha da tabela
                    var row = $('.excluir-btn[data-item-id="' + itemId + '"]').closest('tr');
                    row.remove();
                } else {
                    console.error('Erro ao excluir o item:', response.error);
                }
            },
            error: function(xhr, status, error) {
                console.error('Erro ao excluir o item:', error);
            }
        });
    });
});
</script>

 

  • Curtir 1
Link to comment
Compartilhe em outros sites

  • Casa do Desenvolvedor mudou o título para Como corrigir problema ao capturar 'item.id' em JavaScript com jQuery?

Crie uma conta ou entre para comentar 😀

Você precisa ser um membro para deixar um comentário.

Crie a sua conta

Participe da nossa comunidade, crie sua conta.
É bem rápido!

Criar minha conta agora

Entrar

Você já tem uma conta?
Faça o login agora.

Entrar agora


×
×
  • Create New...