Create Datatable from json data returned from Ajax success

Create Datatable from json data returned from Ajax success

doughngdoughng Posts: 2Questions: 1Answers: 0
edited May 2018 in Free community support

I have an ajax script which sends html form data to backend flask server, the backend server interacts with a database then returns some data as json. How to convert the returned json object to datatable?

$(document).ready(function() {
    $("#submit").click(function(event) {
        $.ajax({
            type: 'POST',
            url: '/query_database',
            data: $('#myform').serialize(),
            success: function(data) {
                //should create datatable from data

            },
            error: function(error) {
                $('#result').html(error);
            }
        });
        event.preventDefault();
    });
});

data in the success is json of this format:

[
      {"id": 1, "city": "ny" }, 
      {"id": 2, "city": "ber" },
      {"id": 3, "city": "la" },
      {"id": 4, "city": "amstd" }
]

Answers

  • J33g73J33g73 Posts: 6Questions: 0Answers: 0

    You can use DataTables to initiate the ajax call. I'd recommend reading the documentation first on how to setup the table and columns to assign the returned data into the columns.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @doughng ,

    Yep, as @J33g73 said, the best is to let DataTables manage the Ajax requests, as in this example here. This section here has other examples that may help.

    If that's not possible for whatever reason, you could just parse the JSON respond and load into an existing table with rows.add().

    Hope that helps,

    Cheers,

    Colin

  • doughngdoughng Posts: 2Questions: 1Answers: 0

    @colin @J33g73 Thanks for the suggestion. I'm a novice so please permit my ignorance. A question; if I let DataTables manage the Ajax requests, how to link that up my with form's event handler $("#submit").click() ?

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi again,

    This example here might be useful, it's from another thread. This is loading the data after a button click - so is probably closer to what you want.

    Cheers,

    Colin

This discussion has been closed.