I’m trying add data to DB and show these data in same page using ajax and jQuery datatable without reloading or refreshing page. My code is saving and retrieving data to/from database. But updated data list is not showing in datatable without typing in search box or clicking on table header. Facing same problem while loading page.
Here is my code
//show data page onload $(document).ready(function() { catTable = $('#cat_table').DataTable( { columns: [ { title: "Name" }, { title: "Level" }, { title: "Create Date" }, { title: "Status" } ] }); get_cat_list(); }); //save new entry and refresh data list $.ajax({ url: 'category_save.php', type: 'POST', data:{name: name,level: level}, success: function (data) { get_cat_list(); }, error: function (data) { alert(data); } }); //function to retrieve data from database function get_cat_list() { catTable.clear(); $.ajax({ url: 'get_category_list.php', dataType: 'JSON', success: function (data) { $.each(data, function() { catTable.row.add([ this.name, this.level, this.create_date, this.status ] ); }); } }); }
Advertisement
Answer
From the documentation,
This method will add the data to the table internally, but does not visually update the tables display to account for this new data.
In order to have the table’s display updated, use the draw() method, which can be called simply as a chained method of the row.add() method’s returned object.
So you success method would look something like this,
$.each(data, function() { catTable.row.add([ this.name, this.level, this.create_date, this.status ]).draw(); });