Why is the whole Web Page refreshing after function call to DataTable

Why is the whole Web Page refreshing after function call to DataTable

LenfantLenfant Posts: 12Questions: 2Answers: 0

I have a Javascript being called as a WebPart on a SharePoint webpage. The script is sourcing data from a SharePoint list and applying the DataTables library functions to format the table nicely. This works nicely when I first open the page and the whole data is sourced from the list and displayed correctly, however when I try to call this function again by a button on the webpage sending in a filter, the filter on the SharePoint list seems to work, the table shown is filtered nicely, however a second or two later the whole webpage is refreshed again and the whole data from the SharePoint is displayed again..

Answers

  • allanallan Posts: 61,972Questions: 1Answers: 10,160 Site admin

    Without a link to the page showing the issue, it is difficult to say I'm afraid. Perhaps you can show us the function you are calling?

    Allan

  • LenfantLenfant Posts: 12Questions: 2Answers: 0
    edited August 2021

    Hi Allan,

    Sorry for the delay, I've found a better solution that fits exactly what I'm trying to do. This is using your example in the following link:

    https://datatables.net/examples/plug-ins/range_filtering.html

    However I unable to understand what I'm doing wrong. I receiving the below error message in the browser console:

    ReferenceError: dataTableClient is not defined

    Please see below js code where I've tried to implement your solution:

    Lawyer: <input type="text" id="Lawyer" >
    <div>
        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="display" id="ClientList">
            <thead>
                <th></th>
                <th>Client Name</th>
                <th>Introducer</th>
                <th>Practice Areas</th>
                <th>Edit/View Client</th>
                <th>View Matters</th>
            </thead>
        </table>
    </div>
    </body>
    <script type="text/javascript">
    $.fn.dataTable.ext.search.push(
        function( settings, mData, dataIndex ) {
            var min = $('#Lawyer').val() ;
            var introducerid = mData[2] ; // use data for the lawyer column
     //       if (introducerid = min) 
            {
                return true;
            }
            return false;
        }
    );
    $(document).ready( function() {
        LoadClientList($('#Lawyer').val());
        
        $('#Lawyer').keyup( function() {
            dataTableClient.draw();
        } );
    });
    function LoadClientList(lawyer) {
        if (lawyer) { filter = '&$filter=(AR_IntroducerId eq '+lawyer+')'; } else filter = '';
        var siteUrl = _spPageContextInfo.webAbsoluteUrl;
        var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('ARClients')/items?$select=ID,AR_ClientName,AR_IntroducerId,AR_PracticeAreas" + filter;
        $.ajax({
            url: oDataUrl,
            type: "GET",
            dataType: "json",
            headers: {
                "accept": "application/json;odata=verbose"
            },
            success: OnSuccess,
            error: OnFailure
        });
    }
    function OnSuccess(data) {
        try {
            var dataTableClient = $('#ClientList').DataTable();
            if (dataTableClient != 'undefined') {
                dataTableClient.destroy();
            }
            
            dataTableClient = $('#ClientList').DataTable({
                "aaData": data.d.results,
                "aoColumns": [
                    {
                      className: 'details-control',
                      orderable: false,
                      searchable: false,
                      mData: null,
                      defaultContent: '<i class = "glyphicon glyphicon-plus-sign"> </ i>',
                      targets: 0
                    },
    
                    { "mData": "AR_ClientName" },
                    { "mData": "AR_IntroducerId" },
                    { "mData": "AR_PracticeAreas.results", "defaultContent": "" },
                    {
                     "mData": "ID",
                     "render": function(mData, type, row, meta) {
                        var returnText = "";
                        var url = _spPageContextInfo.webAbsoluteUrl + "/SitePages/NewClient.aspx?ItemID=" + mData;
                        returnText = "<a target='_blank' href=" + url + ">Click To Edit Client</a>";
                        return returnText;
                        }
                    }
                ],
                "columnDefs": [
                    { "targets": [3],
                      "render": function(mData, type, row, meta) {
                        mData.sort();
                        celldata = mData + '';
                        celldata2 = celldata.split(",").join("<br/>");
                        return celldata2;
                        }
                    }
                ],
                order: [[1, 'asc']]
            });
    

    Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

  • colincolin Posts: 15,177Questions: 1Answers: 2,590

    This is a scoping issue. As you've declared dataTableClient within the OnSuccess() function, it won't be visible within the ready() function. The easiest fix would be to make the variable global,

    Colin

  • LenfantLenfant Posts: 12Questions: 2Answers: 0

    Hi Colin,

    Appreciate your quick response. Unfortunately I'm not a JavaScript programmer, so apologies for the next question if it is a silly question.

    I think I've declared it as a global variable by moving line 51 to between lines 15 & 16. I don't get an error message in the console, however the table does not get redrawn/rebuild with the filtering.

    Any idea why this may be the case?

    Many thanks

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794

    IN line 20 you have this:

     //       if (introducerid = min)
    

    First its a comment which should be causing syntax errors. introducerid = min is an assignment not a comparison. Use either == or === for comparisons. More information about the comparison operators can be found here.

    Kevin

  • 2008jackson2008jackson Posts: 38Questions: 9Answers: 0

    @Lenfant i had the same issue while using search builder buttons. Apparently using datatables via CEWP creates this issue. Solution is to deploy your code on custom aspx pages fully independent of Sharepoint. Hope this resolves your issue. Good luck.

  • LenfantLenfant Posts: 12Questions: 2Answers: 0

    @2008jackson , thanks for your info. Unfortunately I'm not familiar with coding custom aspx pages, still struggling with JavaScript. Do you by any chance have any sample custom aspx pages where DataTables has been used, that I could clone and amend please?

  • LenfantLenfant Posts: 12Questions: 2Answers: 0

    @kthorngren , thank you for your comment.

  • 2008jackson2008jackson Posts: 38Questions: 9Answers: 0

    Hi @Lenfant

    The following is a starter template you may use. Create an aspx file with the code below and upload to Site Assets or any document library in SPO.

    <!DOCTYPE html>    
    <html>    
    <head>    
        <script type="text/javascript" src="SiteAssets/js/jquery-3.5.1.js"></script>        
        <script type="text/javascript" src="SiteAssets/js/jquery.dataTables.min.js"></script>     
        <script type="text/javascript" src="SiteAssets/js/moment.min.js"></script>     
        <script type="text/javascript" src="SiteAssets/js/datetime-moment.js"></script>         
        <script type="text/javascript" src="SiteAssets/js/dataTables.buttons.min.js"></script>      
        <script type="text/javascript" src="SiteAssets/js/buttons.flash.min.js"></script>           
        <script type="text/javascript" src="SiteAssets/js/jszip.min.js"></script>       
        <script type="text/javascript" src="SiteAssets/js/pdfmake.min.js"></script>         
        <script type="text/javascript" src="SiteAssets/js/vfs_fonts.js"></script>           
        <script type="text/javascript" src="SiteAssets/js/buttons.html5.min.js"></script>       
        <script type="text/javascript" src="SiteAssets/js/buttons.print.min.js"></script>       
        <script type="text/javascript" src="SiteAssets/js/dataTables.select.min.js"></script>   
        <script type="text/javascript" src="SiteAssets/js/dataTables.searchBuilder.min.js"></script>    
        <script type="text/javascript" src="SiteAssets/js/dataTables.bootstrap4.min.js"></script>   
        <link rel="stylesheet" type="text/css" href="SiteAssets/css/buttons.dataTables.min.css">  
        <link rel="stylesheet" type="text/css" href="SiteAssets/css/select.dataTables.min.css">  
        <link rel="stylesheet" type="text/css" href="SiteAssets/css/searchBuilder.dataTables.min.css">  
        <link rel="stylesheet" href="SiteAssets/css/bootstrap.css">
        <link rel="stylesheet" href="SiteAssets/css/dataTables.bootstrap4.min.css">
    <script>
    $(document).ready(function() {   
        $.fn.dataTable.moment( 'DD/MM/YYYY' ); 
        loadItems();
    });    
      
    function loadItems() {    
        var oDataUrl = "SPO_Site/_api/web/lists/getbytitle('List_Name')/items?$top=2000&$select=*";    
        $.ajax({    
            url: oDataUrl,    
            type: "GET",    
            dataType: "json",    
            headers: {    
                "accept": "application/json;odata=verbose"    
            },    
            success: mySuccHandler,    
            error: myErrHandler    
        });    
    }    
      
    function mySuccHandler(data) {    
        try {    
            $('#table_id').DataTable({    
                "pageLength": 15,
                "dom": 'Bfrtip',
                "buttons": [ {extend: 'searchBuilder', config: {columns: [0,1],},}, 'copy', 'csv', 'pdf', {extend: 'print',exportOptions: {columns: [0,1]}} ],
                "aaData": data.d.results,
                "aaSorting": [[0, "asc"]],
                "aoColumns": [  
                {    
                    "mData": "NO"    
                },             
                {    
                    "mData": "URL",
                    "mRender": function ( data, type, full )
                    {return '<a href="'+data+'" target="_blank">View</a>';}             
                }
                ]    
            });    
        } catch (e) {    
            alert(e.message);    
        }    
    }    
        
    function myErrHandler(data, errMessage) {    
        alert("Error: " + errMessage);    
    }   
    </script>
    </head>    
    <body>    
       <div class="container-fluid mt-4 mb-4"> 
        <table id="table_id" class="table table-hover table-sm small" cellspacing="0" width="100%">    
            <thead>    
                <tr>    
                    <th>No</th>    
                    <th></th>          
                </tr>    
            </thead>    
        </table>    
        </div>    
    </body>    
    </html>   
    
Sign In or Register to comment.