Ajax DataTable to show a "Loading" Indicator on pre-/post-Render. drawCallback() is called twice

Ajax DataTable to show a "Loading" Indicator on pre-/post-Render. drawCallback() is called twice

Eugene_BEugene_B Posts: 19Questions: 8Answers: 0

For an Ajax DataTable, I need to show a "Loading..." overlay on Pre-Render and hide it on Post-Render.

Sounds simple and the following solution works,

// Show Loading Overlay on pre-render (drawCallback gets called twice both before and after render, strangely)
"drawCallback" : function(settings) {
    $('#loadingProgressOverlay').show();
}, 
// Hide Loading Overlay on post-render (initComplete gets called only once at the very end)
"initComplete": function(settings, json) {
    $('#loadingProgressOverlay').hide();
},

But just as the following user found, drawCallback gets called twice both before & after the render . So this solution isn't clean. How can I isolate just the pre-render moment?
https://datatables.net/forums/discussion/8852/run-a-function-after-ajax-request-finished

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    Use the preXhr event. This way your loading message starts before the Ajax request.

    Kevin

  • Eugene_BEugene_B Posts: 19Questions: 8Answers: 0

    Hi, the preXhr event never gets called in my code. drawCallback does get called but preXhr does not. I verified it as follows. I see the drawCallback alert but not the preXhr one.

    $('#myStudies').DataTable(
            {
                "pageLength": 10,
                "responsive" : true,
                "processing" : true,
                "serverSide" : false,
                "stateSave" : true,
                "ajax" : {
                    url : '/app/loadStudies',
                    dataSrc :  '',                  
                    error: function(jqXHR, textStatus, errorThrown) {
                        handleSystemError(jqXHR, textStatus, errorThrown);
                    }
                },
                "drawCallback" : function(settings) {
                    // TEST
                    alert('drawCallback');
    
                }, 
                "preXhr" : function(settings) {
                    // TEST
                    alert('preXhr');
    
                },              
    
                "initComplete": function(settings, json) {
                    alert('initComplete');
                },
    
  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922
    Answer ✓

    ITs an event not an initialization option. Use the syntax in the docs and place it before the Datatables init code. Like this:

    $('#myStudies')
        .on('preXhr.dt', function ( e, settings, data ) {
            ....
        } )
        .DataTable( {
    ....
    

    Kevin

This discussion has been closed.