简体   繁体   中英

Using jQuery on external loaded DataTable after AJAX refresh

So I have on my page a div with id="machine-content", which I use to display various info about my machines. Mainly, I display information in tables. I am trying to use DataTables ( https://datatables.net/ ), but I have problem initializing the table. After click on action (ie "show me repairs", "show me workhours"), I load a table element from external html and fill it with data through AJAX according to chosen action. So here's how my files look.

In index.php (jquery and datatables are loaded in head):

<script src="data.js"></script>

...
<div id="machine-content" class="col-md-9" style="float:right">
</div>  
...

External html is super simple:

<h1 id="machine-content-h1"></h1>
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>

I then have data.js that controls index.php. There, I handle clicks to actions and loading of table through AJAX. All the data is loaded correctly but when I want to initialize a DataTable (to get search field, paging, etc.) it doesnt work. As far as I know, I have to initialise it after the data is loaded, anyway I also tried initialising it before. Here is data.js:

//EXAMPLE of handling chosen action with button click
//I TRIED putting //I TRIED putting $.('#example').DataTable(); HERE
//wrapped in $(document).ready

$('#arentals').click(function(){
            $( '#machine-content' ).load("/gui/machines/machines/templates/table.html", function() {
                load_service_table("RENTALS");      
     });
}); 

function load_service_table(action){
    var action_url;

    switch(action) {
        case 'REPAIRS':
            action_url='/gui/machines/machines/show_services.php';
            break;
        case 'RENTALS':
            action_url='/gui/machines/machines/show_rentals.php';
            break;
        case 'REVENUES':
            action_url='/gui/machines/machines/show_revenues.php';
            break;
        default:
            action_url='/gui/machines/machines/show_hours.php';
    }

    $.ajax({
            url: action_url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            type: "POST",
            success: function(data) {
                //I TRIED putting $.('#example').DataTable(); HERE
                $( '#machine-content-h1' ).text(action);
                $( '#example' ).html(data); 
                //I ALSO TRIED putting $.('#example').DataTable(); HERE
            }       
    });
    //AND HERE
}

PHP functions are simple and in AJAX return only head and body elements of table, so I guess there is no problem. So my question is: How can I initialize this thing? I mean, if I am able to set html to #example in AJAX success function, why can't I initialise the same element there? Any help would be deeply appreciated.

EDIT
I always get this error: jquery.dataTables.min.js:65 Uncaught TypeError: Cannot read property 'aDataSort' of undefined

SOLUTION

I only added $('#machine-content').find('#example').DataTable(); to AJAX success function which now looks like this:

$.ajax({
            url: action_url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: "html",
            type: "POST",
            success: function(data) {

                $( '#machine-content-h1' ).text(action);
                $( '#example' ).html(data); 
                $('#machine-content').find('#example').DataTable();
            }       
    });

datatable has a build-in ajax method

$('#myTable').DataTable( {
    ajax: '/api/myData'
} );

https://datatables.net/manual/ajax#Loading-data

or use:

$('#machine-content').find('.table').DataTable();

I know this post is older so probably of no help to you now but for anyone else who comes across this.

Something like the following should work:

var adminUsers = {

list: () => {

var action = 'list_users';
var url = base_url+'index.php/admin/users/io';
var data = { }

var response = ajaxRequest.post(action, url, data);

response.then(
    function(obj){
        var data = JSON.parse(obj);
        console.log(data);
        //console.log(data.data.result);
        $.each(data.data, function(i,e){
            var html = '';
            html = html + '<tr>';
            html = html + '<td>'+e.id+'</td>';
            html = html + '<td>'+e.username+'</td>';
            html = html + '<td>'+e.first_name+'&nbsp;'+e.last_name+'</td>';
            html = html + '<td>'+e.status+'</td>';
            html = html + '<td>'+e.locked+'</td>';
            html = html + '<td>'+e.uuid+'</td>';
            html = html + '</tr>';
            $('#users-list tbody').append(html);
        });

        $('#users-list').DataTable(adminUsers.dataTable());
    },
    function(jqXHR, textStatus, errorThrown){
        ajaxRequest.error(jqXHR, textStatus, errorThrown);
    });
},
dataTable: () => {
var config = {
        initComplete : function() {

            $("#users-list_filter").detach().appendTo('#search');
            $("#users-list_length").detach().appendTo('#display_length');
            $("#users-list_length").attr('style', 'margin-right:10px;');
            $("#users-list_filter input").addClass('form-control');

        },
        language: { 
            search: "",
            searchPlaceholder: 'Search...' 
        }
    }        

    return config;
}

};

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