Problems loading a Datatable in Page Load with Javascript

Asked

Viewed 1,174 times

1

I’m a beginner with Javascript and I’m having a problem when the Datatable of my Index is loaded.

inserir a descrição da imagem aqui

If I open a section, on my Index, and put the JS code inside it, everything works perfectly.

@{
    ViewData["Title"] = "Gerenciar Situações de Pessoa";
}

<div class="panel animsition">
    <div class="page-header">
        <h1 class="page-title">@ViewData["Title"]</h1>
        <ol class="breadcrumb">
            <li><a asp-action="Index" asp-controller="Home">Home</a></li>
            <li class="active">situacoes-gerenciamento/listar-todos</li>
        </ol>
        <div class="page-header-actions">
            <div class="btn-group btn-group-sm"
                 role="group">
                <a id="btnNovo" asp-action="Create" data-modal="" class="btn btn-outline btn-default new" data-toggle="tooltip"
                   data-original-title="Cadastrar Novo" data-container="body">
                    <span title="Cadastrar Novo" class="icon wb-plus"></span> Cadastrar Novo
                </a>
                <button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                        data-original-title="Configurações" data-container="body">
                    <i class="icon wb-settings" aria-hidden="true"></i>
                </button>
                <button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                        data-original-title="Exportar" data-container="body">
                    <i class="icon wb-upload" aria-hidden="true"></i>
                </button>
                <button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                        data-original-title="Importar" data-container="body">
                    <i class="icon wb-download" aria-hidden="true"></i>
                </button>
                <button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                        data-original-title="Imprimir" data-container="body">
                    <i class="icon wb-print" aria-hidden="true"></i>
                </button>
                <button type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                        data-original-title="Pesquisa Avançada" data-container="body">
                    <i class="icon wb-search" aria-hidden="true"></i>
                    <span class="hidden-xs">Pesquisa Avançada</span>
                </button>

            </div>
        </div>
    </div>

    <div class="page-content">

        <table id="pessoaSituacaoTable" class="table table-striped table-bordered center-header " cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th>
                        Id
                    </th>
                    <th>
                        Descrição
                    </th>
                    <th>
                        Tipo de Pessoa
                    </th>
                    <th>
                        Ações
                    </th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<div class="modal fade modal-primary" id="modalPessoaSituacao" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog" style="width: 45%; height: 500px;">
        <div class="modal-content">
            <div id="contentModal"></div>
        </div>
    </div>
</div>

@section scripts {
    
    <script type="text/javascript">


        $(function () {

        $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
        var table = $("#pessoaSituacaoTable").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            //"dom": '<"top"i>rt<"bottom"lp><"clear">',
            "ajax": {
                "url": '@Url.Action("getPessoaSituacao", "PessoaSituacao")',
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [
            { className: "align-center", "targets": [3] },
            { className: "align-right", "targets": [0] }
        ],
            "columns": [
                { "data": "id", "name": "Id", "autoWidth": true },
                { "data": "descricao", "name": "Descricao", "autoWidth": true },
                { "data": "pessoaTipoDescricao", "name": "PessoaTipo", "autoWidth": true },
                {
                    "data": null, "name": "Action", "defaultContent": '<a title="Editar" asp-action="Edit" data-modal="" data-id="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
                    '<a title="Detalhes" asp-action="Details" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
                    '<a title="Excluir" asp-action="Delete" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
                    '<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>', "autoWidth": true
                }
            ],
            "language": {
                "sEmptyTable": "Nenhum registro encontrado",
                "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                "sInfoPostFix": "",
                "sInfoThousands": ".",
                "sLengthMenu": "_MENU_ resultados por página",
                "sLoadingRecords": "Carregando...",
                "sProcessing": "Processando...",
                "sZeroRecords": "Nenhum registro encontrado",
                "sSearch": "Pesquisar",
                "searchPlaceholder": "Digite algo...",
                "oPaginate": {
                    "sNext": "Próximo",
                    "sPrevious": "Anterior",
                    "sFirst": "Primeiro",
                    "sLast": "Último"
                },
                "oAria": {
                    "sSortAscending": ": Ordenar colunas de forma ascendente",
                    "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }

        });

        $('.search-input').on('keyup change', function () {
            var index = $(this).attr('data-column'),
                val = $(this).val();
            table.columns(index).search(val.trim()).draw();
        });


        });

   
}

PROBLEM: If I transfer the code to a JS script and refer it to my Index, it does not work and keeps displaying the error message I quoted above. What am I doing wrong?

//Meu Arquivo PessoaSituacao.js

 $(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca os elementos do atributo data-modal e o vincula ao evento click
    $('a[data-modal]').on('click', function (e) {
      // Abre a janela modal com o formulário solicitado 
        openmodal(this.href);
        return false;
    });
    $('#modalPessoaSituacao').on('hidden.bs.modal', function () {
        $('#contentModal').html('');
    });

    $(function () {

        $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
        var table = $("#pessoaSituacaoTable").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            //"dom": '<"top"i>rt<"bottom"lp><"clear">',
            "ajax": {
                "url": '@Url.Action("getPessoaSituacao", "PessoaSituacao")',
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [
                { className: "align-center", "targets": [3] },
                { className: "align-right", "targets": [0] }
            ],
            "columns": [
                { "data": "id", "name": "Id", "autoWidth": true },
                { "data": "descricao", "name": "Descricao", "autoWidth": true },
                { "data": "pessoaTipoDescricao", "name": "PessoaTipo", "autoWidth": true },
                {
                    "data": null, "name": "Action", "defaultContent": '<a title="Editar" asp-action="Edit" data-modal="" data-id="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
                    '<a title="Detalhes" asp-action="Details" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
                    '<a title="Excluir" asp-action="Delete" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
                    '<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>', "autoWidth": true
                }
            ],
            "language": {
                "sEmptyTable": "Nenhum registro encontrado",
                "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                "sInfoPostFix": "",
                "sInfoThousands": ".",
                "sLengthMenu": "_MENU_ resultados por página",
                "sLoadingRecords": "Carregando...",
                "sProcessing": "Processando...",
                "sZeroRecords": "Nenhum registro encontrado",
                "sSearch": "Pesquisar",
                "searchPlaceholder": "Digite algo...",
                "oPaginate": {
                    "sNext": "Próximo",
                    "sPrevious": "Anterior",
                    "sFirst": "Primeiro",
                    "sLast": "Último"
                },
                "oAria": {
                    "sSortAscending": ": Ordenar colunas de forma ascendente",
                    "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }

        });

        $('.search-input').on('keyup change', function () {
            var index = $(this).attr('data-column'),
                val = $(this).val();
            table.columns(index).search(val.trim()).draw();
        });


    });
    
});


function openmodal(url) {
    // Faz uma requisição Get e carrega o formulário na janela modal
    $('#contentModal').load(url, function () {
        $('#modalPessoaSituacao').modal({
            keyboard: true
        }, 'show');
         //Enviar o foco para campo Descrição
         $('#modalPessoaSituacao').on('shown.bs.modal', function(event) {
             $("#txtDescricao").focus();
         });   
       // Vincula o evento submit
        bindForm(this);
    });
}
function bindForm(dialog) {
     // Vincula o formulário na janela modalcom o evento submit
    $('form', dialog).submit(function () {
        if ($(this).valid()) {
             // Realiza uma querisição ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Se a requisição for satisfatória, a página atual é recarregada
                    if (result.success) {
                        window.location = window.location;
                        window.location.reload(); //Ajuda na exclusao, atualizando o grid

                    } else {
                        $('#contentModal').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        } else {
            return false;
        }
    });
}

  • Tries to take its function from within $(Document). ready() and puts it as an independent function.

  • Hello Maycon! I took out take inside the block that you suggested, but continues the same error... I do not know very well of Javascript... I find it strange that this function without a name... gives the impression that it performs without being called.... :(

1 answer

0


$(document).ready(function(){});

and

$(function(){}); //modo abrevidado do ready

are the same thing, so you can’t call one inside the other. The best is to use the one you like best.

$(function(){
  //seus códigos jquery
});
function funcoesJS(){
  //seu código
}

Reference: - https://www.w3schools.com/jquery/jquery_syntax.asp - http://learn.jquery.com/using-jquery-core/document-ready/

======== what your code would look like =========

//Meu Arquivo PessoaSituacao.js

 $(document).ready(function () {
    $.ajaxSetup({ cache: false });
    // busca os elementos do atributo data-modal e o vincula ao evento click
    $('a[data-modal]').on('click', function (e) {
      // Abre a janela modal com o formulário solicitado 
        openmodal(this.href);
        return false;
    });
    $('#modalPessoaSituacao').on('hidden.bs.modal', function () {
        $('#contentModal').html('');
    });

    $('.dataTables_filter input').attr('placeholder', 'Search...').hide();
    var table = $("#pessoaSituacaoTable").DataTable({
        "processing": true, // for show progress bar
        "serverSide": true, // for process server side
        "filter": true, // this is for disable filter (search box)
        "orderMulti": false, // for disable multiple column at once
        //"dom": '<"top"i>rt<"bottom"lp><"clear">',
        "ajax": {
            "url": '@Url.Action("getPessoaSituacao", "PessoaSituacao")',
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [
            { className: "align-center", "targets": [3] },
            { className: "align-right", "targets": [0] }
        ],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "descricao", "name": "Descricao", "autoWidth": true },
            { "data": "pessoaTipoDescricao", "name": "PessoaTipo", "autoWidth": true },
            {
                "data": null, "name": "Action", "defaultContent": '<a title="Editar" asp-action="Edit" data-modal="" data-id="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row"><span class="icon-2x wb-edit"></span></a> |' +
                '<a title="Detalhes" asp-action="Details" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row"><span class="icon-2x wb-search"></span></a> |' +
                '<a title="Excluir" asp-action="Delete" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row"><span class="icon-2x wb-trash"></span></a> |' +
                '<a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico"><span class="icon-2x wb-time"></span></a>', "autoWidth": true
            }
        ],
        "language": {
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "searchPlaceholder": "Digite algo...",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
            },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
            }
        }

    });

    $('.search-input').on('keyup change', function () {
        var index = $(this).attr('data-column'),
            val = $(this).val();
        table.columns(index).search(val.trim()).draw();
    });

});


function openmodal(url) {
    // Faz uma requisição Get e carrega o formulário na janela modal
    $('#contentModal').load(url, function () {
        $('#modalPessoaSituacao').modal({
            keyboard: true
        }, 'show');
         //Enviar o foco para campo Descrição
         $('#modalPessoaSituacao').on('shown.bs.modal', function(event) {
             $("#txtDescricao").focus();
         });   
       // Vincula o evento submit
        bindForm(this);
    });
}
function bindForm(dialog) {
     // Vincula o formulário na janela modalcom o evento submit
    $('form', dialog).submit(function () {
        if ($(this).valid()) {
             // Realiza uma querisição ajax
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    // Se a requisição for satisfatória, a página atual é recarregada
                    if (result.success) {
                        window.location = window.location;
                        window.location.reload(); //Ajuda na exclusao, atualizando o grid

                    } else {
                        $('#contentModal').html(result);
                        bindForm();
                    }
                }
            });
            return false;
        } else {
            return false;
        }
    });
}
  • I understand Wilson... I’ve tried to use it as an independent function, but it didn’t work... Either I’m putting the block in the wrong place or there’s something wrong conflicting...

  • The header of my datatable is loaded first, then the rows are created using JS... I created a function Function myDataTable(){.... } and I’m trying to call it in all possible locations after the grid is loaded... only it’s not working tb... :(

  • arranged your code for better understanding of what I wanted to inform, regarding the header, you have already checked in the source code generated by the browser the sequence of the imported files, jquery,bootstrap,jquery ui, etc...if they are in the right order, confirmed that the file reference path is correct? Which browser you use Chrome or Firefox?

  • Hummmm.. I use Google Chrome. This sequence I did not check no. I did according to your suggestion and Datatable started to work Querei (Until appeared the "Processing..."), but then appeared the error window (as I mentioned in the post) e o as linhas não foram carregado... Only the header loaded.

  • The File is referenced correctly: <script src="~/js/entries/peopleSituacao/peopleSituacao.js"></script>... The other tb files are correctly referenced, because before, I was using datatable, but as I had to refactor it to optimize the searches, began the problems... Amazing that if the script is in the same Index works.... if it mixes with the others of the file gives problem...

  • I solved it! Since the error was related to Ajax, I checked that the path was configured with Razor ("url": '@Url.Action("getPessoaSituacao", "Pessoasituacao")') and when I copied the block to a JS Script Razor does not work rsrssr I just changed the url to ("url": '/situacoes-gerenciamento/getPessoaSituacao') and it worked 100%. Thank you :)

  • Perfect, the path of files if they are automatically edited sometimes cause problems.

Show 2 more comments

Browser other questions tagged

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