2

I am just learning Flask. I am trying to get a JSON object through a jQuery call into flask. My html look like this,

<html>
  <head>
    <title>Passenger</title>
    <style type="text/css"></style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  </head>
  <body>
    <div>
      <form onsubmit="return false">
        <input class="name" type="text" placeholder="Name">
        <input class="submit" type="submit" placeholder="Go">
      </form>
    </div>
    <script>
    $("input.submit").click(function(e){
        $.post( "/save", {name: $("input.name").val(), time: "2pm"});
    });
    </script>
 </body>
</html>

The Flask app file looks like,

from flask import Flask
from flask import redirect, url_for, jsonify
from flask import request
import json
app = Flask(__name__)

@app.route('/')
def home():
  return redirect(url_for('static',filename='index.html'))

@app.route('/save', methods=['PUT','POST'])
def get_name():
  print request.json
  return request.json

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

Running this code returns None. I am expecting to get back the JSON object [{name: $("input.name").val(), time: "2pm"}]. Thanks.

1 Answer 1

7

The problem is that the jquery post is not using the data type of json. You can see that by printing out the request content_type:

print request.content_type
application/x-www-form-urlencoded; charset=UTF-8

Change the Javascript to post json, and request.json should be populated with json as you expect.

var data = JSON.stringify({name: $("input.name").val(), time: "2pm"});
$.ajax("/save", {
    data: data,
    contentType : "application/json",
    type : "POST"
});

Notice that after changing the JS code, request.content_type will be application/json

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! got it. Is it possible to convert the data I get back into json. How would the function change in that case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.