Events not firing on ajax function

Events not firing on ajax function

mxmauromxmauro Posts: 3Questions: 1Answers: 0

Hi, I don't remember experiencing this issue in previous releases (I update the code from GitHub directly)

My tables listens to preDraw.dt and draw.dt events. If the ajax option is an url, events fires as expected but if it is a function, it doesn't.

Data is rendered successfully and no console errors. Also adding preDraw and draw as callback functions has no effect.

Trying to follow the code, I see jquery's trigger are called but the event callback isn't. What can I do?

Regards,
Mauro.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi Mauro,

    I gave this a quick blast here, and as you can see, the events are triggering with this ajax function. Would you be able to provide an example where the problem occurs, please?

    Cheers,

    Colin

  • mxmauromxmauro Posts: 3Questions: 1Answers: 0

    Hi Colin, found the problem. My code looks like this:

    $('#my_table').DataTable({
        "ajax": function (data, callback, settings) {
            var response = {};
    
            response.recordsTotal = 1;
            response.recordsFiltered = 1;
            response.draw = settings.iDraw;
            response.data = [];
                
            var val = [];
            val[0] = "test data";
            response.data[0] = val;
    
            callback(response);
        }
    }).on('preDraw.dt', function () {
        //do something
    }).on('draw.dt', function () {
        //do something
    });
    

    The problem is DataTable's initialization code renders the "ajax" data before returning so, at that time, preDraw and draw events are not registered. When I redraw the table, events triggers fine.

    Not sure if I should open a GitHub issue or this is an expected behavior (although couldn't find where it is documented)

    Regards,
    Mauro.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Good find. I'm not sure either, I could argue it either way, one @allan methinks.

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin
    Answer ✓

    Its due to the fact that your function is synchronous. Ajax is typically async (the first "A" in the acronym), so normally the events would have been added by the time the Ajax response comes in from the server. But in this case, when you call callback() the events haven't yet been added.

    Adding them before you initialise the table allows them to execute as expected: http://live.datatables.net/razoqevi/1/edit .

    Allan

  • mxmauromxmauro Posts: 3Questions: 1Answers: 0

    Hi @allan thank you for the tip. It worked! Didn't know one is able to set the "on" events before the initialization.

    Thank you @colin too

This discussion has been closed.