1

Hi I have a DataTables DataTable object which requests json data via an ajax call. Each object inside the json data has a property called state that can be one of a number of values. Ultimately, I'd like to create several (Data)tables, one for each state without having each table request the same data via ajax again and again. For now, I haven't managed to make a single table filter out the rows with incorrect state yet and I'd like to solve this problem first.

The DataTable object defined as follows:

$(document).ready(function () {
    var table = $('#example').DataTable({
        data: example,
        ajax: {
            url: "{{ callback_url }}",
            dataType: 'json',
            dataSrc: '',
        },
        createdRow: function (row, data, index) {
        },
        columns: [{
            data: "Type"
        }, {
            data: "State",
        }
        }]
   });
});

I want to filter the data that comes from the ajax call based on a parameter (e.g. "if (row.State == 'new') {...};"). How can I do that? Does datatables have a function that can be passed to filter each row?

I really need several tables which show data from the same ajax callback but in different states (e.g. a "New" table, an "Old" table etc.). How can I do this without requesting the same json data again and again for each table rendered? Ideally I can store the ajax in a variable but with the async process I'm not sure how this will work out.

1 Answer 1

2

You can use one ajax and store the data, and than create each datatable.

Example:

$(document).ready(function () {
  var data = null;
  $.ajax(URL, {
    dataType: 'json',
    success: function(ajaxData){
        data = ajaxData;

      newData = data.filter(function(item){ return item.State == "New"});
      oldData = data.filter(function(item){ return item.State == "Old"});

      var newTable = $('#newTable').DataTable({
        data: newData,
        });

      var oldTable = $('#oldTable').DataTable({
        data: newData,
        });

    }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.