I have deployed an app for a school project with basically takes in a user's handwritten digit and then shows the digit on a screen based on some machine learning algorithm.
The user's handwritten digit is stored as a 28x28 JavaScript array and is sent back to the flask app through a post request:
submit_button.onclick = () => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
window.location.replace("/");
}
};
xhr.open("POST", "/submit");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(printGrid()));
clearGrid();
};
The Flask app then processes the array through a function and updates a global variable digit
based on the output of the function:
@app.route("/submit", methods=['POST'])
def submit():
global digit
digit = process_digit(request.get_json())
return "ok"
The "/" route then returns an updated html template with the digit.
In the development server the webpage does what I expect it to do and only reloads once the digit has been processed based on the xhr.onreadystatechange
I set in the JavaScript file.
However, when deployed to heroku, the webpage reloads a short while after the submit button has been pressed but sometimes the digit shown on the screen would not be updated and I would have to do 1 - 3 reloads for it to show to correct value.
Is there anything I could do to solve this issue? I'm new to web development so if anyone could point me to the right resources or point out the mistakes I have made that would be very much appreciated!
EDIT:
Maybe in short what I would like to ask is this: what is the best way to take input from the user using javascript i.e. the 2D array, send it to a python program for processing and then update the webpage properly based on the output from the python program?