Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to append data into existing data table using ajax

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.

like image 465
Suhail Mumtaz Awan Avatar asked Nov 04 '15 10:11

Suhail Mumtaz Awan


2 Answers

"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();
like image 73
davidkonrad Avatar answered Sep 19 '22 04:09

davidkonrad


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.. )

like image 32
Vanojx1 Avatar answered Sep 22 '22 04:09

Vanojx1