Question

Once submitted a form containing a list of numbers, I need to extract (from a JSON file) the result of a simple calculation, performed on that list and output that result inside a <div></div> tag, in the current page.

Here below the Flask Python code with the submitted list of numbers obtained via getlist. The result of the calculation is finally converted into JSONvia jsonify.

from flask import Flask,render_template, request, jsonify
app = Flask(__name__)

data = [
('t', 0, 'a'),
('t', 0, 'b'),
('t', 0, 'c'),
('t', 0, 'd')
]

@app.route('/', methods=['GET', 'POST'])
def index():
    entries=[]
    for (i,v) in enumerate(data):
        entries.append(data[i][2])
    return render_template('test.html', entries=entries)


@app.route('/_numbers', methods=['GET', 'POST'])
def numbers():
    a = request.form.getlist('a')
    print a
    L=0
    v=0
    an=0
    for L,v in enumerate(a):
        an+=float(v)
    return jsonify(res=an)

if __name__ == '__main__':
    app.debug = True
    app.run()

test.html file looks like:

{% extends "test0.html" %}
{% block body %}

<h2>Get the sum of 4 numbers</h2>
<form action="{{ url_for('numbers')}}" method=post>
    {% for L in entries %}

              <input type=float size=5 name=a>

              {% if loop.last==True %}             
                  <input class="btn btn-primary" type="submit" value="Calc" id="calculate"> 
                  </form>
              {% endif %}
    {% endfor %}

{% endblock %}

Upon submitting, I get the correct answer in the form of a JSON file (e.g.):

{
  "res": 10.0
}

How to extract the obtained value and display it via JQuery ? I've tried getJSON but with no success. Thanks for any help.

Was it helpful?

Solution

If you want to insert the result in the current page then you have to submit the form over Ajax, and then you get the JSON response in the completion callback.

Take a look at the AjaxForm plugin for jQuery, which can transform the submit button in your HTML form to an Ajax submit. Below is a short example adapted from the plugin's documentation:

<script> 
    $(document).ready(function() { 
        // bind 'myForm' and provide a simple callback function 
        $('#myForm').ajaxForm(function(response) { 
            var result = jQuery.parseJSON(response);
            $('#someDiv').innerHTML = result.res
        }); 
    }); 
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top