Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables draw() without ajax call

I'm trying to resize jquery Datatables to fit the screen size. Datatables runs in server-side mode (property "serverSide": true). When the window size is changed I make recalculation of new datatables height and then call draw(false) to redraw the layout of datatable.

Unfortunately, the draw() method makes an ajax call and this makes the solution unusable, because it shows "processing" and takes time to get the data on every small window change.

How to redraw datatables layout without calling AJAX? I don't need to refresh data, I just want to redraw the table.

like image 941
Sergey Zhukov Avatar asked Jun 28 '15 07:06

Sergey Zhukov


2 Answers

I replaced the calling of table.draw(false) to table.columns.adjust(). It renders the table with new height and width without an AJAX call, so the issue is resolved for me. However it would be nice to know the proper way to render dataTables without an AJAX call in server-side mode.

like image 105
Sergey Zhukov Avatar answered Nov 09 '22 01:11

Sergey Zhukov


I faced same problem. I solved it with fake AJAX response. Here's some code to show how it works:

Variables:

var skipAjax = false, // flag to use fake AJAX
    skipAjaxDrawValue = 0; // draw sent to server needs to match draw returned by server

DataTable AJAX definition:

ajax: {
    url: ajaxURL,
    type: 'POST',
    data: function(data) { //this function allows interaction with data to be passed to server
        if (skipAjax) { //if fake AJAX flag is set
            skipAjaxDrawValue = data.draw; //get draw value to be sent to server
        }

        return data; //pass on data to be sent to server
    },
    beforeSend: function(jqXHR, settings) { //this function allows to interact with AJAX object just before data is sent to server
        if (skipAjax) { //if fake AJAX flag is set
            var lastResponse = dataTable.ajax.json(); //get last server response
            lastResponse.draw = skipAjaxDrawValue; //change draw value to match draw value of current request

            this.success(lastResponse); //call success function of current AJAX object (while passing fake data) which is used by DataTable on successful response from server

            skipAjax = false; //reset the flag

            return false; //cancel current AJAX request
        }
    }
}

How to use:

skipAjax = true; //set the fake AJAX flag

dataTable.draw('page'); //call draw function of a DataTable requesting to re-draw just the current page
like image 6
Maz T Avatar answered Nov 09 '22 02:11

Maz T