2

I use $.getJSON to retrieve json file, such as purchase.json, and dynamically create a table through processJSON(data), a function to create table dynamically with JSON content. The table id is "example". Next I need to apply dataTable, a jQuery plug-in, to this table so I can apply pagination and other features to the table. The JavaScript I have is -

    $(document).ready(function() {  
        $('#AJAXButton').click(function() {
            $.getJSON('data/purchase.json', function(data) {
                processJSON(data);
            });
        });
    });

    $(document).ready(function() {
        $('#example').dataTable( {
            "sScrollY": "200px",
            "bPaginate": false
        } );
    } );

I was able to create the table with JSON content, but dataTable features were not working. How to adjust my code to make it work?

Thanks for helping me out. C. L.

0

2 Answers 2

4

I'm guessing that your problem is that $('#example').dataTable() is executed before #example is populated. The #example table won't have anything in it until someone presses #AJAXButton and the getJSON finishes; the #example table may exist when .dataTable is called but the datatable won't know about the data you load into the table from your JSON blob.

The solution would be to bind the datatable after the table is filled in:

$(document).ready(function() {  
    $('#AJAXButton').click(function() {
        $.getJSON('data/purchase.json', function(data) {
            processJSON(data);
            $('#example').dataTable({
                "sScrollY": "200px",
                "bPaginate": false
            });
        });
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much mu is too short. I really like your analysis which helps me understand why the table did not response to dataTable. Now the table has all the great scrollingTable features I am looking for. So binding dataTable after the table is filled is the key.
@C.L.: "Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime." Don't forget to accept answers to your questions by clicking the checkmark beside the answer.
Thank you mu is too short. From your analysis, I definitely learn how to fish in this situation. Now I have much better understanding on how to run multiple jQuery functions when one rely on the outcome of another function.
0

or you could just use the built-in method for adding json data to the table using sAjaxSource.

Since your button is hard coded with a json data value, you could just use the button to show/hide the table.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.