0

This is the route on app.py

app.route('/analyze', methods=['POST'])
async def analyze(requestArg):
    img_data = await requestArg.form()
    img_bytes = await (img_data['file'].read())
    img = open_image(BytesIO(img_bytes))
    prediction = learn.predict(img)[0]
    result(str(prediction))

I'm trying to send the str(prediction) to the result() function on static/js/script.js here

function result(str) {
    $(".pd-result").show();

    var resultText = $(".text")
    switch (str) {
        case "emotion":
            text.html("angry");
            break;

        default:
            break;
    }
};

I've tried to just directly call result(str(prediction)) but it doesn't work.

1
  • 3
    a) you can't just mix JavaScript and Python randomly (or non-randomly) b) the Python code runs on the server, and that JS code is client-side code and therefore runs in the user's browser. You need to use $.post() to make a request to the server's /analyze route, then process the result in the success callback. Commented Sep 8, 2020 at 18:30

1 Answer 1

1

In app.py return prediction:

app.route('/analyze', methods=['POST'])
async def analyze(requestArg):
    img_data = await requestArg.form()
    img_bytes = await (img_data['file'].read())
    img = open_image(BytesIO(img_bytes))
    prediction = learn.predict(img)[0]
    return prediction

Within your js file call you function on a successfull post request:

$(() => {
    Var data = {...};
    $.post("/analyze", data)
        .done((prediction)=>{
            result(prediction)
        }))
})

See here: https://api.jquery.com/jquery.post/

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

2 Comments

You are right - you have to use ` $.post() `. This should work since you are already using jQuery. I fixed my code.
Thanks! I'm not really familiar with Ajax so I wasn't sure what went wrong.

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.