luqita
luqita

Reputation: 4077

Datatables: Adding an extra row on real time?

I am trying to add a new row to a table, after it is loaded (since I need to retrieve some data), but the new row just shows 'undefined'. It looks like this:

$('#example tr').each( function () {
                id = this.id.substr(4);
                var result2;
                if (id.length > 0) {
                    $.post('get_stuff.php', {id: id}, function(result) {
                        result2 = result;
                    }); 
                    oTable.fnOpen( this, result2, "info_row_");
                }
            } );

The above opens the new rows and writes 'undefined' in them. If, however, before the fnOpen call I add an alert(result2) the result is shown in the alert and then written to the row. How can I solve this?

Upvotes: 0

Views: 1260

Answers (2)

PeeHaa
PeeHaa

Reputation: 72652

Your $.post() request is asynchronous.

So the info is written while it is still being requested.

You could either add:

$.ajaxSetup({async:false}); before the .post() call or use .ajax() with async: false option.

.post() is just a shorthand version of .ajax()

Or you could write the vakue in the success callback of the .post() function.

$.post('get_stuff.php', {id: id}, function(result) {
  //result2 = result; // don't know if you still need the result2 var somewhere else. If that's the case you should use one of the other approaches (as stated above)
  oTable.fnOpen( this, result, "info_row_");
}); 

Upvotes: 3

Tules
Tules

Reputation: 4915

This will wait until the Ajax call has completed successively before executing the function.

$('#example tr').each( function () {
            id = this.id.substr(4);
            if (id.length > 0) {
                $.ajax({
                    url:'get_stuff.php', 
                    data: "id="+id, 
                    success: function(result) {
                        oTable.fnOpen( this, result, "info_row_");
                    }
                }); 

            }
        } );

Upvotes: 2

Related Questions