user1368182
user1368182

Reputation: 473

datatables fnDraw makes multiple ajax requests

My jquery datatables seem to be posting twice when I manually redraw (via a button click) - how can I prevent datatables from doing this?

Here is my client side code:

$(document).ready(function () {
    dataTable = $('#Results').dataTable({
        "bLengthChange": true,
        "bFilter": false,
        "bSort": true,
        "bInfo": true,
        "bAutoWidth": false,
        "sPaginationType": "bootstrap",
        "sDom": "ftrpli",
        "bServerSide": true,
        // "sAjaxSource": "AjaxControllerAction",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "UserId", "value": $('#UserId').val() });
            aoData.push({ "name": "Data", "value": $('#Data').val() });
            aoData.push({ "name": "Location", "value": $('#Location').val() });
        },
        "fnServerData": function (sSource, aoData, fnCallback) {
            showProgress();

            var headers = {};
            headers['__RequestVerificationToken'] = token;
            alert('zzzz');

            $.ajax({
                dataType: 'json',
                type: 'POST',
                //url: sSource,
                url: 'AjaxControllerAction',
                data: aoData,
                headers: headers,
                success: function (json) {
                    hideProgress();

                    fnCallback(json);
                },
                error: function (json) {
                    hideProgress();
                }
            });
        },
        "fnDrawCallback": function () { hideProgress(); },
        "bProcessing": false,
        "aoColumns": [
                { "sName": "NAME",
                    "fnRender": function (oObj) {
                        return '<a href="Details/' +
                        oObj.aData[0] + '">' + oObj.aData[0] + '</a>';
                    }
                },
                { "sName": "DATA" },
                { "sName": "DATA1" },
                { "sName": "DATA2" },
                ]
    });
}
);

$("#SearchForm").on("submit", function (event) {
    event.preventDefault();
    // this sends the request twice ??
    dataTable.fnDraw();
});

I know it's hitting my AjaxControllerAction twice, from using both firebug (I see the xmlhttprequest twice) and that it's hitting my action twice by setting a breakpoint. I can't find any reason why it would do this. Thanks!

Upvotes: 3

Views: 8135

Answers (4)

Tchello
Tchello

Reputation: 11

My solution

I used the parameter from datatables: iDisplayStart -> Display start point in the current data set.

Step 1: Create a global variable to persiste datas.

var options = {
    jsonResultDataTableFromServer: {},
    iDisplayStart: -1,
    iDisplayLength : -1
};

Step 2: Change ajax fnServerData function to:

"fnServerData": function(url, data, callback) {
               //data[3] i.e iDisplayStart
               //data[4] i.e iDisplayLength
               if (options.iDisplayStart != data[3].value || options.iDisplayLength != data[4].value) {
                    options.iDisplayStart = data[3].value;
                    options.iDisplayLength = data[4].value;

                    $.ajax({
                        "url": url,
                        "data": data,
                        //"success": callback,
                        "success": function(json) {
                            options.jsonResultDataTableFromServer = json;
                            callback(json);
                        },
                        "contentType": "application/x-www-form-urlencoded; charset=utf-8",
                        "dataType": "json",
                        "type": "POST",
                        "error": function() {
                            alert("DataTables warning: JSON data from server failed to load or be parsed. " +
                                "This is most likely to be caused by a JSON formatting error.");
                        }
                    });
                } else {
                    options.jsonResultDataTableFromServer.sEcho = eval(options.jsonResultDataTableFromServer.sEcho) + 1;
                    callback(options.jsonResultDataTableFromServer);
                }

                return false;
            },

Upvotes: 1

westcoastmilt
westcoastmilt

Reputation: 23

I had a similar problem using jQuery dataTable 1.9 (legacy version). I was calling table.dataTable to prepare the AJAX POST connection and then I was calling fnDraw. Turns out the second call to fnDraw was not needed at all and that eliminated the second Ajax request (both table.dataTable and fnDraw were placed in a $(document).ready function within the jsp that displayed the table). The table.dataTable alone handled all functionality (calling controller with new criteria). The initial controller call showed the default view. When the user clicked the sort icons for a column the controller was called again to pass the new sort criteria and generate the proper SQL query. When the user clicked pagination icons the controller was called and generated the proper SQL query for pagination.

Upvotes: 0

Tom
Tom

Reputation: 689

That's weird. dataTable.fnDraw(); should send one AJAX call. Maybe you should look into the plugins script and see what happen there. But first try new version :)

I'm trying to disable that AJAX call on redraw. If I find solution I'll post it here

Upvotes: 0

Arjun
Arjun

Reputation: 21

This could be due to the fact that you have used similar name "dataTable" as the variable you have initialised the datatables with

dataTable = $('#Results').dataTable({

and this might be the reason why datatables is drawing twice when you manually redraw. Try to change the variable name and see.

Upvotes: 0

Related Questions