1

I submitted a form data to a backend Flask application as ajax post request. Backend process uses data to query database then returns json object back to Ajax. How to construct datatable from this json object?

My Ajax post request:

$(document).ready(function() {
    $("#submit").click(function(event) {
        $.ajax({
            type: 'POST',
            url: '/process',
            data: $('#myform').serialize(),
            success: function(response) {
                //response looks like this: 
                //[{"country": "USA", "code": "1007-01" },{"country": "UK", "code": "1100-04" }]

            }
        });
        event.preventDefault();
    });
});

My flask application

@app.route('/process', methods=["POST"])
def process():
    if request.method == 'POST':
       country = request.form['id'].encode("utf-8")
       #query database and store result in dict
       result = query_database(country)
       return jsonify(result)
DougKruger
  • 4,424
  • 14
  • 41
  • 62
  • 1
    This seems like more of a jQuery question than a Flask question. – ollien May 20 '18 at 01:15
  • Possible duplicate of [Using jQuery to build table rows from Ajax response (Json)](https://stackoverflow.com/questions/17724017/using-jquery-to-build-table-rows-from-ajax-response-json) – Mikey May 23 '18 at 13:39

1 Answers1

1

Initialize your datatable with your ajax call as datasource

let datatable = $('#my-table').DataTable({
    ajax: {
        url: '/process',
        method: 'POST',
        data: {
            $('#myform').serialize()
        } 
    }
});

now you just need to format your response like this

{ 
    data:[/*your Data*/]
}
BraveButter
  • 1,408
  • 9
  • 22