skip to Main Content

I am trying to build a simple Tic-Tac-Toe web app. I would like to connect my frontend to my backend logic where I will be running a python script. I believe flask is what I need to use to create a localserver & ajax can be used with jquery to connect button press with python logic. Everything I tried has returned errors or at most I am getting a html page response when I should be getting a json file.

I am very tired and have spent all day trying to figure this out with no success so any help would be greatly appreciated.

My folder structure looks like this:
folder structure

My .js code:

$(document).click(function (e) {
    if ($(e.target).attr("id") == "head") {
        var tossVal = $(e.target).attr('value')
        passCoinToss(tossVal)

        var soundbyte = document.createElement("audio")
        soundbyte.src = "/static/Assets/click1.mp3"
        soundbyte.play()
        remvCoinflip()
    } })


function passCoinToss(Value) {
    $.ajax({
        url: "http://127.0.0.1:5000//test",
        type: "GET",
        success: function(response){
            alert(response);
        }
    }); }

My python script with flask

# Using flask for simple webhook initialization in order to run our webpage.
from flask import Flask, redirect, url_for, render_template, request, jsonify
from static.Backend.algorithm import coinToss
import os, json

# Declaring the app
app = Flask(__name__)


# Render homepage
@app.route("/")
def main():
    return render_template('index.html')


# Route for CoinToss
@app.route("/test", methods=['GET', "POST"])
@cross_origin()
def test():
    data = {"picked": "1"}
    return json.dumps(data)


if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)

2

Answers


  1. Chosen as BEST ANSWER

    SOLUTION

    Must Json.dumps the data first and then jsonify

    # Route for CoinToss
    @app.route("/test", methods=['GET', "POST"])
    def test():
        data = {"picked": "1"}
        j = json.dumps(data)
        return jsonify(j)
    

    Check to make sure that the url is correct

    function passCoinToss(Value) {
        $.ajax({
            url: "/test",
            type: "GET",
            contentType: "application/json",
            success: function (response) {
                alert(response);
            }
        });
    }
    

  2. @app.route("/test", methods=['GET', "POST"])
    @cross_origin()
    def test():
        data = {"picked": "1"}
        return jsonify(data)
    

    If you want to return a json data, you can use the jsonify function of flask builtin function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search