简体   繁体   中英

Initialize two different tables with a single AJAX call

I'm trying to render two different tables but with a single AJAX call.

How to initialize two different tables but using the same source of JSON data? The only different of these two tables is that I filter the rows by a specific key in JSON .

Currently my code looks like this.

var t = $('#adminKeysTable').DataTable( {
            "ajax": {
                "url": getKeysById,
                "dataSrc": function(json) {
                    var rows = [];
                    for (var i=0;i<json.keys.length;i++) {
                        if (json.keys[i].privileges == '32') 
                            rows.push(json.keys[i]);
                            allAdminKeys.push(json.keys[i].key);
                    }
                    return rows;
                }
            },
            "columns": [
                { "data": null },
                { "data": "name" },
                { "data": "key" },
                { "data": null }
            ]               
        } );

var tt = $('#apiAccessKeyTable').DataTable( {
            "ajax": {
                "url": getKeysById,
                "dataSrc": function(json) {
                    var rows = [];
                    for (var i=0;i<json.keys.length;i++) {
                        if (json.keys[i].privileges != '32') 
                            rows.push(json.keys[i]);
                    }
                    return rows;
                }
            },
            "columns": [
                { "data": null }, 
                { "data": "name", "className": "editable" }, 
                { "data": "key" }, 
                { "data": "externalUser", "className": "editable" }, 
                { "data": "privilegesArray", "className": "edit-privileges" },
                { "data": null }, 
                { "data": null } 
            ]
        } );

The issue with my current code is that it tends to take longer time to load the second table after the first one has done loading. I'm assuming that's because I'm making two AJAX calls at the same time?

I'm new to AJAX . So not sure how to make only one call to the GET request, and use that JSON data to initialize two separate tables.

Appreciate if someone can guide me. Thanks.

Taking different into consideration, once you get data, you can store the data to the different variable and pass the data view to likewise you're passing.

var tt = $('#apiAccessKeyTable').DataTable( {
        "ajax": {
            "url": getKeysById,
            "dataSrc": function(json) {
                var t1rows = [];
                var t2rows = [];
                for (var i=0;i<json.keys.length;i++) {
                    if (json.keys[i].privileges != '32') {
                        t1rows.push(json.keys[i]); // Changed section
                    } else {
                        t2rows.push(json.keys[i]); // changed section
                    }

                }
                return rows;
            }
        },
        "columns": [
            { "data": null }, 
            { "data": "name", "className": "editable" }, 
            { "data": "key" }, 
            { "data": "externalUser", "className": "editable" }, 
            { "data": "privilegesArray", "className": "edit-privileges" },
            { "data": null }, 
            { "data": null } 
        ]
    } );

Hope this helps!

I seriously have no experience with that DataTable method from jQuery. But you could do something like this:

$.ajax({
     url: getKeysById,
     success: function(json) {
         var t1rows = [];
         var t2rows = [];

         for (var i = 0; i < json.keys.length; i++) {
             if (json.keys[i].privileges != '32') {
                 t1rows.push(json.keys[i]); // Changed section
             }
             else {
                 t2rows.push(json.keys[i]); // changed section
             }
          }
          callback(t1rows, t2rows);
      }
});


var callback = function(data1, data2){
    $('#apiAccessKeyTable').DataTable({columns: []}); //add your data here: t1rows
    $('#adminKeysTable').DataTable({columns: []}); //add your data here: t2rows;
}

You first execute a standalone ajax call and render your tables in the success handler.

You should look at how to add a data from that jQuery datatable that didnt come from an internal ajax request. I'm assuming it'll be relatively easy. Something like:

var callback = function(data1, data2){
$('#adminKeysTable').DataTable({
    dataSrc: data1,
    columns: []
});

$('#apiAccessKeyTable').DataTable({
    dataSrc: data2,
    columns: []
});
}

?

This can be even further simplified but for the sake of being relatively similar to your code I'm gonna leave it as is.

You do 1 ajax call, split data based on condition and load Datatable with respective JSON

Something like this

var t1rows = [];
var t2rows = [];


function splitData(){

    $.ajax({
         url: getKeysById,
         success: function(json) {
         for (var i=0; i < json.keys.length ; i++) {
             if (json.keys[i].privileges != '32') {
                 t1rows.push(json.keys[i]); // Changed section
             }
             else {
                 t2rows.push(json.keys[i]); // changed section
             }
          }
          // load Datatables
        loadDatatable1();
        loadDatatable2();


          }
    });
}


function loadDatatable1(){

    $('#apiAccessKeyTable').dataTable({
        data: t1rows,
        columns: [
            { data: 'userID' },
            { data: 'userName' }
        ]
    });
}


function loadDatatable2(){

    $('#adminKeysTable').dataTable({
        data: t2rows,
        columns: [
            { data: 'userID' },
            { data: 'userName' }
        ]
        });
}

i have modified a fiddle from answer of this Datatable - Insert JSON data to the table

You can try something like in this fiddle

https://jsfiddle.net/gx3ktawn/311/

HTML

<button id="getResults">Get Results</button>
<table id="my_logs"></table>
<table id="my_logs2"></table>

Script

var myTable = $('#my_logs').DataTable({
    "paging": true,
    "lengthChange": true,
    "searching": true,
    "ordering": true,
    "info": true,
    "autoWidth": true,
    "data": [],
    "columns": [{
        "title": "Date",
        "data": "log_time"
    }, {
        "title": "User Name",
        "data": "user_name"

    }, {
        "title": "Class",
        "data": "class_name"

    }, {
        "title": "Function",
        "data": "class_function"

    }, {
        "title": "Action",
        "data": "action_title"

    }, {
        "title": "Description",
        "data": "action_description"

    }]
});
var myTable2 = $('#my_logs2').DataTable({
    "paging": true,
    "lengthChange": true,
    "searching": true,
    "ordering": true,
    "info": true,
    "autoWidth": true,
    "data": [],
    "columns": [{
        "title": "Date",
        "data": "log_time"
    },  {
        "title": "Class",
        "data": "class_name"

    }, {
        "title": "Function",
        "data": "class_function"

    }, {
        "title": "Description",
        "data": "action_description"

    }]
});

$(document).ready(function() {
    $("#getResults").click(function() {
        $.ajax({
            url: 'https://api.myjson.com/bins/ml2k2',
            success: function(logs) {
                myTable.clear();
                $.each(logs, function(index, value) {
                    myTable.row.add(value);
                });
                myTable.draw();
        myTable2.clear();
                $.each(logs, function(index, value) {
                    myTable2.row.add(value);
                });
                myTable2.draw();
            },
            error: function(jqXHR, textStatus, ex) {
                alert(textStatus + "," + ex + "," + jqXHR.responseText);
            }
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM