Initializing DataTable After Div Element Loaded

Initializing DataTable After Div Element Loaded

chboccachbocca Posts: 90Questions: 14Answers: 1

DataTables is a fantastic app.

Thank you!

Have been able to successfully incorporate several features/plug-ins.

For a newbie like me, easy and straightforward to incorporate options.

But I'm stuck and hopefully someone can offer path forward.

I believe the issue I'm seeing is one of timing.

I need to delay initialization until after my HTML div element is loaded, which is where I have my table in HTML format.

How do I do that?

My example goes like...

<html>
<head>
    <link rel="stylesheet"  href=".../jquery.dataTables.css">
    <script type="text/javascript" src=".../jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src=".../jquery.dataTables.min.js"></script>
</head>
<body>
         <div id='example'></div>
         <script type="text/javascript">
             $(document).ready(function() {
                   $('#example').dataTable( {
                   } );
              } );
          </script>
</body>
</html>

The table data in HTML formal is created upstream using js. But, it is not finished before I attempt to initialize DataTables, so the table just outputs as a static table.

The HTML looks like...

<table id='example' class='display'><thead>....</thead><tbody>...</tbody></table>

If I pass the table data as a string via js to the HTML page like...

<script type="text/javascript">
    var html = localStorage.getItem("html");
    document.write(html);
</script>

The DataTables works great, but that creates other timing issues.

Again, basically I believe I simply need to delay initialization until after my div element is loaded.

Thanks in advance.

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,678Questions: 1Answers: 10,497 Site admin

    Hi,

    Thanks for your kind words and for picking up the priority support options.

    I think you are right - this is a case of timing, or perhaps more specifically code ordering.

    What I would suggest is that you place the DataTable creation black immediately after your document.write statement, so it might look like:

    <script type="text/javascript">
        var html = localStorage.getItem("html");
        document.write(html);
    
        $(document).ready(function() {
            $('#example').dataTable();
        } );
    </script>
    

    That way, the table will be created after the document has the required HTML. I've kept the $(document).ready() function as this is good practice to ensure that the table is only created when the document has been loaded.

    This works as localStorage is synchronous. If it were asynchronous (e.g. there was an Ajax call to get the data) then you would need to delay the creation of the DataTable further, until the async call was complete. In such cases a callback is required (the mechanism for which is normally provided by whatever is making the async call).

    Regards,
    Allan

  • chboccachbocca Posts: 90Questions: 14Answers: 1

    Ha!

    Thank you Allan!

    Yes, this method is how I actually tailored DataTables to my application, which includes scrollx, column reorder, download, column fixed, etc. Wonderful, wonderful. A huge enhancement, so I am happy to help contribute.

    Unfortunately, the output is always the last result, because of the synchronicity issue you state. The html in localStorage has not yet been updated. (Hit reload and get the current result.) I thought loading from a div element would address that since it gets loaded upstream by js via the

    document.getElementById('example').innerHTML = html;
    

    command after the new result is computed.

    In any case, yes, sounds like I need to do a callBack just do not know how to implement it in my case. I don't use an Ajax call. I just load the html variable (or dynamic table) in the js once computed through innerHTML above or localStorage.

    The sequence goes like...

    Start on example.html page and select example criteria...hit submit. Then
    example.html page calls example.php page that calls example.js page to calculate result and load the html, which is then output by the example.php page, rendered beautifully by DataTables.

    Only it is the last search result!

    The example.js page has not finished updating the latest result before it gets output on the example.php page.

    I tried setting a flag in local.storage, which is easy to do. But then how do I delay this

     <script type="text/javascript">
        var html = localStorage.getItem("ihtml");  //7apr15
        document.write(html);
     </script>
    

    from running until after the flag is set?

    In meantime, I will set up a test case for you to see the exact issue and email you the log-in.

    Very much appreciate the support.

  • allanallan Posts: 63,678Questions: 1Answers: 10,497 Site admin
    Answer ✓

    The html in localStorage has not yet been updated.

    I see - so the html variable either doesn't exist, or contains the results from the last search.

    Using document.write seems a little risky for this to my mind - but I don't have the full picture yet. Yes, please if you could drop me an e-mail with a link, that would be really useful.

    Regards,
    Allan

  • chboccachbocca Posts: 90Questions: 14Answers: 1

    Thank you Allan for helping me resolving this...code works great now using the callback code additions you suggested for the traditional div id output method.

    For rest of the board, the solution was something like...

    output = function(input, "#example", callback) {
        ...various calculations here;
        callback();
    };
    
    output(input, "#example", function () {
        $('#example').DataTable( { ... } );
    } );
    

    Now that I have the "basic bones" working, looking forward to using more of the ajax/search/formatting features organic to DataTables.

    Keep doing good stuff!

    Really appreciate your work and support.

  • chboccachbocca Posts: 90Questions: 14Answers: 1

    @yeehee.

    Let me see if I can provide a more helpful example of using callback, based on Allan's guidance.

    It's done in conjunction with the jQuery ajax function...

    http://api.jquery.com/jquery.ajax/

    On your html or php output page (perhaps linked to js page(s))...

    <script type="text/javascript">
    
       function output( callback ) {
       
          $.ajax( {
             success: function () {
                calcs here...
            render html string here...   
                document.getElementById('example').innerHTML = html;    
                callback();
         }  
          } );
          return;
       }
    
    </script>
    
    ...
    
    <div id=example></div>
    
    ...
    
    <script type="text/javascript">
    
       output( function() {                 
          $(document).ready(function() {
             $('#example').DataTable({
             });
          }
       });
    
    </script>
                
    

    So, if I understand this correctly, the DataTables execution awaits completion of the cacls via the ajax callback function.

    Build a simple example until you get it...then, go from there.

    Hope this helps.

  • allanallan Posts: 63,678Questions: 1Answers: 10,497 Site admin

    Looks good to me. I would probably put the $(document).ready() part on the outside, rather than inside output: eg:

    $(document).ready(function() {
       output( function() {                
         $('#example').DataTable({ ... });
       } );
    } );
    

    but that it really just a style thing :-)

    Allan

This discussion has been closed.