最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Correct way to append data into existing data table using ajax - Stack Overflow

programmeradmin3浏览0评论

Introduction

I am working with the functions where user search donor organizations by name.

Data loads in DataTable, paging enabled and works fine for the initial data load. (Data load with initial call from jquery is about 100 records)

Lately, i have tried to implement the ajax method, which is suppose to load "next 100 records" and append to the existing records(now record reaches at 200 aprox).

Problem

Record loading on ajax call is loaded into datatable but displays this recent record on current page(no paging applied on it).

When user change the page to navigate between records, this recent record disappear.

I am just manipulating DOM elements, i think i have to pass it to datatable, yes?

Complete Code(just copy and paste whole code to test,cdn libs used)

<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->

    <head>
        <title>Demo : Test</title>
        <!-- Meta -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="stylesheet" href=".10.9/css/jquery.dataTables.min.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-3">
                    <form>
                        <input type="text" id="searchParam" name="searchParm" placeholder="enter search param">
                        <br>
                        <input type="submit" value="Submit" onclick="searchDonors(document.getElementById('searchParam').value); return false;">
                    </form>
                    <br />
                </div>
                <div class="col-md-9">
                    <div id="demoApim"><table id="demoApi"><thead><tr><td>Organization Name</td><td>Address</td></tr></thead><tbody id="tBody"></tbody></table></div>
                </div>
                <div class="col-md-3" id="searchBtn"><input type="submit" value="Load Next 100 Records" onclick="loadNext(); return false;"></div>
            </div>
        </div>
        <script type="text/javascript" src=".1.4.js"></script>
        <script type="text/javascript" src=".10.9/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript">
            var count;
            $('#searchBtn').hide();
            $(document).ready(function () { $('table').hide();});
            function searchDonors(searchParam) {
                window.searchDonorsParam = searchParam;
                count = 100;
                var request = new XMLHttpRequest();
                request.open("GET", ":" + searchParam + "*%20AND%20country:US&&page_size=100&page=1", false);
                request.send();
                var xml = request.responseXML;
                //$.each(xml, function (key, val) {
                var oName = xml.getElementsByTagName("organization_name");
                //console.log(oName);
                var oAddress = xml.getElementsByTagName("address_line_1");
                var counts = xml.getElementsByTagName("organization_name").length;
                for (var i = 1; i < counts; i++) {
                    var html = [];
                    html.push('<tr><td>', oName[i].innerHTML)
                    html.push('</td><td>', oAddress[i].innerHTML)
                    html.push('</td></tr>')
                    $("#tBody").append(html.join(''));
                }
                $('#demoApi').DataTable();
                $('table').show();
                $('#searchBtn').show();
                //});
                //console.log(oName);
                //console.log(oAddress);
            }
    
            function loadNext()
            {
            if (count = 100)
            {
                $.ajax({
                    url: ":" + searchDonorsParam + "*%20AND%20country:US&&page_size=100&page=2",
                    method: "GET",
                    dataType: "xml",
                    success: function (xml) {
                        var xmlDoc = $.parseXML(xml),
                        $xml = $(xmlDoc);
                        console.log(xml.getElementsByTagName("organization_name"));
                        var oNameMore = xml.getElementsByTagName("organization_name");
                        var oAddressMore = xml.getElementsByTagName("address_line_1");
                        var countsNew = xml.getElementsByTagName("organization_name").length;
                        var html;
                        for (var i = 1; i < countsNew; i++) {
                            html = [];
                            html.push('<tr><td>', oNameMore[i].innerHTML)
                            html.push('</td><td>', oAddressMore[i].innerHTML)
                            html.push('</td></tr>')
                            $("#tBody").append(html.join(''));
                        }
                        },
                    error: function () {
                        console.log("call failled");
                    }
                });
            }
            }
        </script>
    </body>
    </html>

If someone have idea about that problem please let me know, any kind of help or reference will be appreciated.

Introduction

I am working with the functions where user search donor organizations by name.

Data loads in DataTable, paging enabled and works fine for the initial data load. (Data load with initial call from jquery is about 100 records)

Lately, i have tried to implement the ajax method, which is suppose to load "next 100 records" and append to the existing records(now record reaches at 200 aprox).

Problem

Record loading on ajax call is loaded into datatable but displays this recent record on current page(no paging applied on it).

When user change the page to navigate between records, this recent record disappear.

I am just manipulating DOM elements, i think i have to pass it to datatable, yes?

Complete Code(just copy and paste whole code to test,cdn libs used)

<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->

    <head>
        <title>Demo : Test</title>
        <!-- Meta -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-3">
                    <form>
                        <input type="text" id="searchParam" name="searchParm" placeholder="enter search param">
                        <br>
                        <input type="submit" value="Submit" onclick="searchDonors(document.getElementById('searchParam').value); return false;">
                    </form>
                    <br />
                </div>
                <div class="col-md-9">
                    <div id="demoApim"><table id="demoApi"><thead><tr><td>Organization Name</td><td>Address</td></tr></thead><tbody id="tBody"></tbody></table></div>
                </div>
                <div class="col-md-3" id="searchBtn"><input type="submit" value="Load Next 100 Records" onclick="loadNext(); return false;"></div>
            </div>
        </div>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript">
            var count;
            $('#searchBtn').hide();
            $(document).ready(function () { $('table').hide();});
            function searchDonors(searchParam) {
                window.searchDonorsParam = searchParam;
                count = 100;
                var request = new XMLHttpRequest();
                request.open("GET", "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchParam + "*%20AND%20country:US&&page_size=100&page=1", false);
                request.send();
                var xml = request.responseXML;
                //$.each(xml, function (key, val) {
                var oName = xml.getElementsByTagName("organization_name");
                //console.log(oName);
                var oAddress = xml.getElementsByTagName("address_line_1");
                var counts = xml.getElementsByTagName("organization_name").length;
                for (var i = 1; i < counts; i++) {
                    var html = [];
                    html.push('<tr><td>', oName[i].innerHTML)
                    html.push('</td><td>', oAddress[i].innerHTML)
                    html.push('</td></tr>')
                    $("#tBody").append(html.join(''));
                }
                $('#demoApi').DataTable();
                $('table').show();
                $('#searchBtn').show();
                //});
                //console.log(oName);
                //console.log(oAddress);
            }
    
            function loadNext()
            {
            if (count = 100)
            {
                $.ajax({
                    url: "http://graphapi.firstgiving.com/v1/list/organization?q=organization_name:" + searchDonorsParam + "*%20AND%20country:US&&page_size=100&page=2",
                    method: "GET",
                    dataType: "xml",
                    success: function (xml) {
                        var xmlDoc = $.parseXML(xml),
                        $xml = $(xmlDoc);
                        console.log(xml.getElementsByTagName("organization_name"));
                        var oNameMore = xml.getElementsByTagName("organization_name");
                        var oAddressMore = xml.getElementsByTagName("address_line_1");
                        var countsNew = xml.getElementsByTagName("organization_name").length;
                        var html;
                        for (var i = 1; i < countsNew; i++) {
                            html = [];
                            html.push('<tr><td>', oNameMore[i].innerHTML)
                            html.push('</td><td>', oAddressMore[i].innerHTML)
                            html.push('</td></tr>')
                            $("#tBody").append(html.join(''));
                        }
                        },
                    error: function () {
                        console.log("call failled");
                    }
                });
            }
            }
        </script>
    </body>
    </html>

If someone have idea about that problem please let me know, any kind of help or reference will be appreciated.

Share Improve this question edited Mar 10, 2022 at 17:30 meowulf 3771 gold badge6 silver badges15 bronze badges asked Nov 4, 2015 at 10:59 Suhail Mumtaz AwanSuhail Mumtaz Awan 3,4838 gold badges47 silver badges77 bronze badges 2
  • 1 If incorporated correctly, DataTables will load the first 100 records, and the next on paging automatically. If setup correctly, you can add search box, headers, etc to DataTables as configurations. Read DataTables Ali reference. – Alex Commented Nov 4, 2015 at 11:08
  • @Alex thanks for valuable input, i will look into it .... – Suhail Mumtaz Awan Commented Nov 4, 2015 at 11:15
Add a comment  | 

2 Answers 2

Reset to default 12

"I think i have to pass it to datatable, yes?". Yes. The correct way is to go through the API. Without using the API, dataTables cannot be aware of whatever changes you have made to the underlying <table> and therefore your recent records disappear :

var table; //outside your function scopes

in searchDonors() :

table = $('#demoApi').DataTable();

in loadNext() use row.add() instead of injecting markup to <tbody> :

for (var i = 1; i < countsNew; i++) {
   table.row.add([oNameMore[i].innerHTML, oAddressMore[i].innerHTML]);
}
table.draw();

yes ofc modify DOM its not enought for datatables, you need to use datatables function to access data, use this:

initialize the table:

var myTable = $('#demoApi').DataTable();

then

myTable.row.add( [oNameMore[i].innerHTML,oAddressMore[i].innerHTML] );

all the data are stored inside datables settings object, updating the DOM don't change the current table settings so you will lose you change after any table redraw ( search, change page, ecc.. )

发布评论

评论列表(0)

  1. 暂无评论