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.