Why does datatables not call draw() after doing a server side call?

Why does datatables not call draw() after doing a server side call?

taltal Posts: 5Questions: 3Answers: 0

I'm using datatables 1.11.3 with Django.
My table will be processing a lot of data, so I'm using server-side processing (or trying to).
My datatables initialization is fairly simple:

$(document).ready( function () {
    $('#my_table').DataTable({
        processing: true,
        serverSide: true,
        searchDelay: 1000,
        deferRender: true,
        ajax: {
            type: "POST",
            url: "...",
            data: {
                additional_data: "...",
            },
        },
    });
});

Django has a view that returns JSON:

@csrf_exempt
def my_view(request):
    return JsonResponse({
        "draw": 1,
        "recordsTotal": 10,
        "recordsFiltered": 2,
        "data": [
            ["a", "b", "c", "d"],
            ["e", "f", "g", "h"],
        ]
    })

Seems like it should work.
This is what happens instead:

When the page loads, it makes an AJAX call, Django returns the data, and it shows the table with the data with no issues.
Then when I enter text into the DataTables search textbox, a "Processing" message pops up over the table (as expected), Django receives the request and returns the JSON again. It sends it back to the browser, but the datatables doesn't update. It still has the old data in the table, with the "Processing" message above it.

The Network tab of my firefox's dev tools shows that as I write text into the datatables search text box, it sends the request to Django, and django sends a proper JSON reply. I'm not sure why Datatables isn't re-drawing the table with the new data when it receives this reply.

Am I doing something wrong?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946
    Answer ✓

    return JsonResponse({
    "draw": 1,

    Looks like you are hardcoding the draw parameter. Its a sequence number that Datatables uses to make sure it receives the correct response. The response shoule contain the same value that is sent. See the Server Side Processing docs for more details.

    Kevin

  • taltal Posts: 5Questions: 3Answers: 0

    I saw the draw parameter return in the AJAX response in this main example, but didn't really have a good understanding of what it was doing. I thought it was a boolean. 1 to redraw the table when the response is received, or 0 not to. I couldn't find the documentation for it. Thanks for providing the link. This is definitely what I was missing.

Sign In or Register to comment.