Search code examples
javascriptjquerydatatables

jQuery Datatables - Recursive problem with drawCallback and Search function


I'm facing problems when looking for a customer in the table through the Input Search of the Datatables, because I have a function that adds the ID later in a Form Action, but it is adding the ID several times, I identified that when I click on the button without using the Search no the problem happens, but using Search it adds the ID according to the number of letters inserted in the input.

I've seen similar problems with drawCallback and they suggested using .on("click") instead of .click() but it had no effect.

Follow the code below

$("#list_clients").DataTable({
    "paging": true,
    "lengthChange": true,
    "searching": true,
    "ordering": true,
    "info": true,
    "autoWidth": false,
    "responsive": true,                  
    drawCallback: function (settings) {
        $('.btnNewOrder').on("click", function (e){  
            e.preventDefault();
            alert(0);
            
            var clientId = $(this).data('id');

            // AJAX request
            $.ajax({
                url: "<?= url("commercial/sales/order/new/") ?>" + clientId,
                type: 'post',
                data: {
                    action: "getFieldsOrder",
                },
                success: function(response){  
                    // Add response in Modal body
                    $('#modal-newOrder .modal-body').html(response); 

                    //Exibe Modal
                    $('#modal-newOrder').modal('show');                                    

                    var newFormUrl = $('#newOrderForm').attr('action') + clientId;
                    $('#newOrderForm').attr('action', newFormUrl);
                }
            });
                  
            $('#modal-newOrder').on('hide.bs.modal', function () {
                var newFormUrl = $('#newOrderForm').attr('action');
                newFormUrl = newFormUrl.slice(0, newFormUrl.lastIndexOf('/')) + '/';
                $('#newOrderForm').attr('action', newFormUrl);
            });
        });   
    }
}); 

Solution

  • I was able to solve the recursive problem by adding .off() to the call.

    $('.btnNewOrder').off().on("click", function (e){
    });