-1

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.

Yair
  • 85
  • 1
  • 9

1 Answers1

1

EDIT: the original solution is wrong, and you should refer to the linked question, jQuery posting JSON.

Additional background: Flask wouldn't throw any exception. You can also inspect what Chrome sent with the Network tab (see How can I debug a HTTP POST in Chrome?).

Tatsuyuki Ishi
  • 3,883
  • 3
  • 29
  • 41
  • Hi, thank you for your response. I tried to add what you said but it still don't work. when i check the response in the network tab (I work with Firefox) I get the "Recieved data as None" response. Do you know why? also, sometimes i get a green status, and sometimes grey, which seems like nothing happened or something... – Yair Jul 27 '17 at 14:12
  • Check what you **send** before what you receive. – Tatsuyuki Ishi Jul 27 '17 at 14:14
  • As your question have been flagged as duplicate, please see what the linked question shows. I'm not an expert on jQuery. – Tatsuyuki Ishi Jul 27 '17 at 14:17
  • I tried to check, but the problem is that when i press on the button it seems to refresh the whole page. notice i added to the function a print to the console which should signal that the function doWork() has been executed, but it doesn't print that. instead it reloads the page when sending the signal. is that what suppose to happen? – Yair Jul 27 '17 at 14:17
  • If you need to retain the logs, check "preserve log" in network tab. – Tatsuyuki Ishi Jul 27 '17 at 14:19