简体   繁体   中英

Table not sorting through PHP but sorting inside HTML

I have html table create by a php, I want to sort this table, but no success. If I create the table inside the html the sort work.

<!DOCTYPE html>
<html>
<head>
<title>Teste</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>
 <div class="container mb-3 mt-3" id="inicio">
 </div>


<script>
$(document).ready(function(){
load_list();
$('.mydatatable').DataTable();
function load_list()
{
    var action = "data";
    $.ajax({
        url: "teste.php",
        method:"POST",
        data:{action:action},
        success:function(data)
        {
            $('#inicio').html(data);
        }
    })
}

}); 
</script>
</body>
</html>

Example of table from php:

<?php
if(isset($_POST["action"]))
{
if($_POST["action"]=="data")
{
$output = '
 <table class="table table-striped table-bordered mydatatable" style="width: 100%">
  <thead>
  <tr>
   <th>Tittle</th>
  </tr>
  </thead>
  <tbody>
  <tr>
   <td>data</td>
  </tr>
  <tr>
   <td>date2</td>
  </tr>
  </tbody>
 </table>
 ';
 echo $output;
 }
 ?>

I think the $('.mydatatable').DataTable(); is in the wrong place, I tried my options but only work if the table is inside the html page. Anyone can help me?

As first A in ajax means asynchronous , then your call to $('.mydatatable').DataTable(); happens before real data is loaded via ajax. You should move call to DataTable to success callback:

success:function(data)
{
    // note the order - first you load `html`
    $('#inicio').html(data);
    // after that you have a `.mydatatable` selector available
    $('.mydatatable').DataTable();
}

Table html is not there when you initialize your Datatable.

$(document).ready(function(){
load_list();

function load_list()
{
    var action = "data";
    $.ajax({
        url: "teste.php",
        method:"POST",
        data:{action:action},
        success:function(data)
        {
            $('#inicio').html(data);
            //move this to here
            $('.mydatatable').DataTable();
        }
    })
}

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