python with flask get and post methods using ajax
<p>i am currently developing a food calorie web app and i want to extract data from a mongoDB into an HTML table.</p>

<p>my python code is:</p>

<pre><code>from flask import Flask
from flask import request
import requests
from wtforms import Form, BooleanField, StringField, PasswordField, validators
from flask import render_template, jsonify
import os
from flask import Markup
from contextlib import suppress
from collections import defaultdict
import operator
import re
from collections import Counter
import random
import math
import collections
import pymongo
from pymongo import MongoClient
from flask_table import Table, Col



app = Flask(__name__)

#jsonify(result=str(test[0]))



@app.route('/')
def index():
    return render_template('index.html')


@app.route('/_foods')
def add_numbers():
    connection = MongoClient('&lt;connection string&gt;')
    db = connection.foodnutr

    a = request.args.get('a', 0, type=str)
    test=[]
    for i in db.foods.find( {"Description":{'$regex': a}}):
            test.append(i)

    items = [test[0]["Description"]]



    return jsonify(result=str(test[0]['Description']))




if __name__ == '__main__':
    app.run(host='127.0.0.1', port=2490,debug=True)
</code></pre>

<p>and my HTML file is:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
    &lt;link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
          rel="stylesheet"&gt;
  &lt;script type=text/javascript&gt;
    $(function() {
      $('#calculate').bind('click', function() {
        $.getJSON('/_foods', {
          a: $('input[name="a"]').val()
        }, function(data) {
          $("#result").text(data.result);
        });
        return false;
      });
   });
	

	

&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class="container"&gt;
      &lt;div class="header"&gt;
        &lt;h3 class="text-muted"&gt;Enter a food&lt;/h3&gt;
      &lt;/div&gt;
      &lt;hr/&gt;
      &lt;div&gt;
      &lt;p&gt;
    &lt;input type="text" size="5" name="a" &gt; 
	&lt;input type="submit" value="Submit" onclick="myFunction()"  id="calculate"&gt;
      &lt;/form&gt;
      &lt;/div&gt;
    &lt;/div&gt;
	
	&lt;table id="result"&gt;
 &lt;tr&gt;
        
        &lt;th&gt;id&lt;/th&gt;
        &lt;th&gt;result&lt;/th&gt;
    &lt;/tr&gt;
&lt;/table&gt;
  &lt;/body&gt;
&lt;/html&gt;</code></pre>
</div>
</div>
</p>

<p>currently, i have successfully managed to get the data from the mongoDB into flask in both json, dictionary formats.</p>

<p>What i need, is to get my data into HTML table.</p>

<p>How can i achieve it?</p>

<p>For your current JSON use this code:</p>

<pre><code> $(function() {
    $('#calculate').bind('click', function() {
        $.getJSON('/_foods', {
            a: $('input[name="a"]').val()
        }, function(data) {
            for (key in data) {
                $('#result').append('&lt;tr&gt;&lt;td&gt;' + key + '&lt;/td&gt;&lt;td&gt;' + data[key] + '&lt;/td&gt;&lt;/tr&gt;')
            }
        });
        return false;
    });
});
</code></pre>

<p>But actually this is not nice method to implement. It would be better to change your JSON and use <a href="http://json2html.com/" rel="nofollow">http://json2html.com/</a> jQuery plugin for building table.</p>

<p>Better JSON Schema:</p>

<pre><code>var data = [{
    "name": "Protein(g)Per Measure",
    "value": 22.6
}, {
    "name": "Sugars, total(g)Per Measure",
    "value": 5.72
} {
    "name": "Vitamin E (alpha-tocopherol)(mg)Per Measure",
    "value": 0.0
}]
</code></pre>

<p>In this case using JSON2HTML is recommended:</p>

<pre><code>var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${value}"}
        ]}
    ]}
]};

$('#result').html(json2html.transform(data,transform));
</code></pre>

javascript jquery python html flask