Eric Eric - 3 months ago 12
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__)

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

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

if __name__ == "__main__":
app.run()


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

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

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

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

$.ajax({
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: "email=myemail@gmail.com", status: "OK"}'
console.log(result);
}
});
});

Answer

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: "myemail@gmail.com"} which can be parsed by flask.


To do this without JSON:

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

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