Passing data into flask using Ajax
<p>i am trying to pass some data from html to python using ajax using post request. But the arguments for request are empty.</p>

<p>A simple endpoint, i am trying to print all the arguments that come in the form of request.</p>

<pre><code>@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    else:
        print("post")
        print(request.args)
        return render_template('index.html')
</code></pre>

<p>debug output</p>

<pre><code>post

ImmutableMultiDict([])
127.0.0.1 - - [22/Sep/2016 00:40:12] "POST /enter HTTP/1.1" 200 -
</code></pre>

<p>the ajax function is as below</p>

<pre><code>$(function() {
    $('.button').click(function() {
        var user = $('#userinput').val();
        console.log(user);
        $.ajax({
            url: '/enter',
            data: JSON.stringify( {'user': $('#userinput').val()} ),
            type: 'POST',
            success: on_request_success,
            error: on_request_error,
            })
        });
    });
</code></pre>

<p>the value gets printed in js console. But its not present on python side.</p>

<p>html code</p>

<pre><code>&lt;body&gt;
        &lt;h3&gt;The Chef Bucket&lt;/h3&gt;
        Enter food you like to order.
        &lt;input type="text" name="user_data" id="userinput" /&gt;
        &lt;input type="button" value="Submit" class="button"&gt;

        &lt;div id="userinputdata"&gt; 
            {% if not entered %}
                &lt;h4&gt;&lt;/h4&gt;
            {% else %}
                &lt;h4&gt;{{ entered }}&lt;/h4&gt;
            {% endif %}
        &lt;/div&gt;

    &lt;/body&gt;
</code></pre>

<p>Within render template, you need to specify elements to be filled in within your template.</p>

<p>Instead of this;</p>

<pre><code>@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    else:
        print("post")
        print(request.args)
        return render_template('index.html')
</code></pre>

<p>Try this;</p>

<pre><code>@app.route("/enter", methods=["POST", "GET"])
def enter_data():
    if request.method == "GET":
        return render_template('index.html')
    elif request.method == "POST":
        entered = request.form['entered']
        return render_template('index.html', entered=entered)
    else:
        return render_template('index.html')
</code></pre>

javascript jquery python ajax flask