0

This is my index.html file

<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() {
    // setup the button click
    document.getElementById("theButton").onclick = function() {
        doWork()
    };
}

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

    });
    // stop link reloading the page
 event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<form action = "/result" method = "POST">
    <button id = "theButton" class ="button">
            <span>
                    <i >Click</i>
            </span>
    </button>
<form>

This is my json_io.py file to run Flask:

#!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')

@app.route('/result', methods = ['POST', "GET"])
def worker():
    # read json + reply
    data = request.get_json(force = True)
    print(data)
    return render_template('result.html', result = data[0]["make"])

if __name__ == '__main__':
    # run!
    HOST = '127.0.0.1'
    PORT = 4100

    app.run(HOST, PORT, debug = True)

After running the command line and click on click button. I got what I want in the Chrome console. enter image description here

In order to get into http://127.0.0.1:4100/result , I will comment event.preventDefault(); in index.html. However, when I rerun again, it shows me Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

Are there any ideas on how I can fix this ?

1 Answer 1

1

In the index.html file, make a placeholder that will be filled out by the js code handling your AJAX request:

<span id='ajax_result'>placeholder</span>

Then, in the python code, you don't really need to go through the template and can return a string straight away:

@app.route('/result', methods = ['POST', "GET"])
def worker():
    data = request.get_json(force = True)
    return data[0]['make']

Then, in js, grab the result and put it in the placeholder span:

function doWork() {
    $.post("result", JSON.stringify(cars), function(reply){
        $('#ajax_result').text(reply);
    });
     event.preventDefault();
}

Click the button and enjoy your Porsche!

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

1 Comment

Perfect, thank you for your help. But do you know why the js variable can't be passed to the result page even though it showed on the console ? Is there anyway we can pass it to the result page ? I just want to know it so that I can be more flexible for my projects in the future.

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.