I am new to web programming and I am trying to learn how to send messages between a python server and a JavaScript client.
I found the following guide: http://www.makeuseof.com/tag/python-javascript-communicate-json/, which instruct you how to create a python server using flask and how to send requests to it using AJAX and JQuery.
the server python code (from the guide with modifications):
#!flask/bin/python
import sys
from flask import Flask, render_template, request, redirect, Response
import random, json
app = Flask(__name__)
@app.route('/')
def output():
# serve index template
return render_template('index.html', name='Joe')
@app.route('/receiver', methods = ['POST'])
def worker():
print("execute worker()")
# read json + reply
data = request.get_json()
print("data = "+str(data))
if data is None:
return "Recieved data as None"
result = ''
for item in data:
# loop over every row
result += str(item['make']) + '\n'
return result
if __name__ == '__main__':
# run!
app.run()
The client side (named "index.html", also from the guide with modifications):
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
console.log("started script");
// setup some JSON to use
var cars = [
{ "make":"Porsche", "model":"911S" },
{ "make":"Mercedes-Benz", "model":"220SE" },
{ "make":"Jaguar","model": "Mark VII" }
];
window.onload = function() {
// setup the button click
document.getElementById("theButton").onclick = function() {
doWork()
};
console.log("executed window.onload successfully");
}
function doWork() {
// ajax the JSON to the server
$.post("receiver", cars, function(){
});
// stop link reloading the page
event.preventDefault();
console.log("executed doWork successfully");
}
console.log("ended script");
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>
</html>
When I upload index.html on my local host, it prints to the console all the messages except "executed doWork successfully", which makes sense.
But when I click on the button (a element with id "theButton"), it refreshes the page and does not print that message. also, on the server side I get that "data = None", and when I check the response in the response tab in network in developer tools, sometimes I get "Recieved data as None", and sometimes nothing.
Can anyone help me understand that behavior? I followed this guide step by step but I just can't find my mistake.