Create Datatable from json data returned from Ajax success
Create Datatable from json data returned from Ajax success
doughng
Posts: 2Questions: 1Answers: 0
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" }
]
This discussion has been closed.
Answers
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.
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
@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()
?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