Eric Eric - 1 month ago 5x
Python Question

Pass just one field via AJAX with Flask

I have a VERY simple HTML form with just one

<input type='text'>
field, an email address, that I need to pass back to a Python script via AJAX. I can't seem to receive the value on the other end. (And can all the JSON encoding/decoding be avoided, since there's just one field?)

Here's the code:

from flask import Flask, render_template, request, json
import logging

app = Flask(__name__)

def hello():
return render_template('index.htm')

@app.route('/start', methods=['POST'])
def start():
# next line outputs ""
email = request.json['email'];
# next line ALSO outputs ""
return json.dumps({ 'status': 'OK', 'email': email })

if __name__ == "__main__":

And the Javascript that sends the AJAX from the HTML side--

$( "form" ).on( "submit", function( event ) {

d = "email=" + $('#email').val(); // this works correctly

// next line outputs 'sending data:'
console.log("sending data: "+d);

type: "POST",
url: "{{ url_for('start') }}",
data: JSON.stringify(d),
dataType: 'JSON',
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log("SUCCESS: ");

// next line outputs 'Object {email: "", status: "OK"}'


JSON.stringify is used to turn an object into a JSON-formatted string, but you don't have an object, just a string. Try this:

var d = { email: $('#email').val() };

JSON.stringify(d) will now turn that into a JSON-formatted string:

{email: ""} which can be parsed by flask.

To do this without JSON:

var d = { email: $('#email').val() };
    data: d,
    success: ...

This will turn {email: ""} into and send that as body of the POST request. In Flask, use request.form['email'].