Reputation: 4624
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)
Upvotes: 1
Views: 334
Reputation: 1458
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*/]
}
Upvotes: 1