passing data into callback

passing data into callback

rootmanrootman Posts: 7Questions: 0Answers: 0
edited March 2009 in General

I got a question which isn't directly related to Datatables but i think it's a good place to ask in here.

This is an extract of my code:

for ( var i=0 ; i


  • rootmanrootman Posts: 7Questions: 0Answers: 0
    Hey folks!

    Tonight i shifted around in my sheets and came up with a solution for this problem and I just wanna let you know in case somebody runs into the same problem.
    What I did is I wrote a function:

    function fnAddGroup (id, groupid, groupname, pos)
    $.post('<?=site_url('/adressbuch/add_to_group')?>/' + id + '/' + groupid,
    if ( returned_data)
    var data = oTable.fnGetData(pos);
    oTable.fnUpdate( data[13] + ', ' + groupname , pos, 13 ); /* Single cell */


    I call this function in the loop and pass the current data, that way the callback function sees the local and !current! data of pos!

    greetings :)
  • allanallan Posts: 61,038Questions: 1Answers: 9,953 Site admin
    Hi rootman,

    Looks like you've got this sorted already - nice one! What you are looking for (and have achieved with your function) is closure. The issue was due to the async behaviour of the Ajax request, the Javascript engine had updated the local variable 'pos', which was then out of date for when the async request comes back. So your closure is to make pos local to a different function, thus saving scope. Lovely stuff :-)

    One thing to note is that if there are many Ajax calls to make here, it might be a bit more efficient to group them all into one - the latency over an HTTP request can be quite high, and making lots of small Ajax requests to your server can strain it's resources.

  • rootmanrootman Posts: 7Questions: 0Answers: 0
    Thanks Allan!

    Jep, you are right, thats quite a bunch of requests there. So far I did it this way for some reasons.
    1. I was too lazy to write a new function in php that could handle the bulk request
    2. Still trying to get the hang of things ;)

    In PHP you never really run into problems like this, its all processed in order, nothing async :) So these problems are kinda new for me, just started using jquery and datatables about a week ago. I was one of the guys who never likes JS too much because of the various problems that come with different browsers, but jquery changed my mind and now i love to do as much as possible on the clientside to keep my php simple.

This discussion has been closed.