I'm using Flask (Flask API link) to create a very simple website that takes an 'order_id' and uses a MySQL database (MYSQL - Python API link) in the background to finally return the associated items for that order_id in a table.
It all works well, except that the table only flashes for a second the moment I submit the order_id. It works every time I submit, but the table just won't stay.
My Python (Flask) code:
@app.route('/fetch_order', methods=['POST'])
def fetch_order():
order_id = request.form.get('order_id')
order = connect_db.fetch_order_json(order_id)
order = json.dumps(order)
return order
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True, port=5440)
My JS / jQuery:
$(document).ready( function() {
$("#order_id").submit( function() {
var order_id = $('#order_id :text').val();
var dataString = 'order_id=' + encodeURIComponent(order_id);
var body_rows = [];
var html = '<tr>';
$.ajax({
type: "POST",
data: dataString,
url : "/fetch_order",
success: function(json) {
data = JSON.parse(json);
if (data) {
$.each(data, function (index, data_list) {
data_dict = JSON.parse(data_list);
headers = Object.keys(data_dict);
body_rows += '<tr>';
$.each(data_dict, function (ignore, value) {
body_rows += '<td>' + value + '</td>';
});
body_rows += '</tr>'
});
$.each(headers, function (index, header) {
html += '<th>' + header + '</th>';
});
html += '</tr>';
html += body_rows;
// --> working but only for a second?!
$('#orders_table').append(html);
}; },
error: ...
My html:
<div>
<form id="order_id" accept-charset="utf-8">
<input type="text" name="order_id" autofocus><br>
<input type="button" value="Submit">
</form>
</div>
<div>
<table id="orders_table">
</table>
</div>
The answers to the following questions didn't help me (or I just didn't understand them well enough):
- .show() method is not working like it is supposed to in jquery
- Show hide divs with addClass removeClass works, but just for a second
- jquery append() not working on dynamically added elements
- DropDown Menu won't show for more than a second..not working.
- Populate html table on jQuery success event
- jQuery AJAX each loop using append and html
My gut tells me it has to do with the ($.each())
loops but I just can't seem to figure it out. Any push into the right direction would be greatly appreciated!
EDIT:
- tried to reduce complexity by hardcoding the headers in html to no avail
- tried to rewrite jQuery to JS in case it's a jQuery thing, but it looks like it's not
- tried moving around
$('#orders_table').append(table_html);
, adding .show(), plugging it into ajaxComplete() instead, .. all to no avail
Would really love some help here!