How to get AJAX posted JSON in flask?

Question:

I am following this flask tutorial to learn about building an app in Python.

The tutorial (close to the end) talks about how to get a AJAX posted JSON inside python as follows:

HTML code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
    { "make":"Porsche", "model":"911S" },
    { "make":"Mercedes-Benz", "model":"220SE" },
    { "make":"Jaguar","model": "Mark VII" }
];

window.onload = function() {
    document.getElementById("theButton").onclick = doWork;
}

function doWork() {
    // ajax the JSON to the server
    $.post("receiver", cars, function() {

    });
    // stop link reloading the page
    event.preventDefault();
}
</script>
This will send data using AJAX to Python:
<br/><br/>
<a href="" id="theButton">Click Me</a>

Python Code:

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    return render_template('index.html')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json()
    result = ''

    for item in data:
        # loop over every row
        result += str(item['make']) + 'n'

    return result

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

When I run the script and click on the button ‘Click me’ in the browser, I get the 500 Internal Server Error when I examine the Response in the browser. If I print the data variable, it prints out None in the terminal on the click event. I tried the suggestions given in the comments to use get_json(forced=true) in Python script and stringify the 'cars' JSON in HTML file but in vain.

Asked By: zingsy

||

Answers:

It looks like you didn’t specify the content type of your post request look what is said in the official documentation:

By default this function will return None if the mimetype is not
application/json
but this can be overridden by the force parameter.

you need also to serialize you cars object to json object .

you can do something like this :

function doWork() {
    // ajax the JSON to the server
    $.ajax({
        type: 'POST',
        url: '/receiver',
        data: JSON.stringify (cars),
        success: function(data) { alert('data: ' + data); },
        contentType: "application/json",
        dataType: 'json'
    });
    // stop link reloading the page
    event.preventDefault();
}
Answered By: Espoir Murhabazi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.