Flask not redirecting after POST request sent from JavaScript

I am new to JavaScript and http requests maybe I am doing something pretty wrong here, hope someone can help me.

I am trying to send a POST request to my flask application using XMLHttpRequest, heres the JS code:

finishBuy.addEventListener('click', () => {

     price = price * 1000000000000000000
              // Some code
        function (txHash) {
            console.log('Hash: ' + txHash)

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/addTokens");
            xhr.setRequestHeader('Content-Type', 'application/json');
                hash: txHash
            window.location.href = "/addTokens"
    .catch((error) => console.error);})

And this is my python code

def index():
return render_template("index.html")

@app.route("/addTokens", methods=["GET", "POST"])
def addTokens():
  if request.method == "GET":

        return render_template("checkingPayment.html")

  if request.method == "POST":
        hash = request.get_json()

        print(f"Hash: {hash}")

        print("Redirecting to index")
        return redirect(url_for('index'))

Flask prints “Redirecting to index” but the browsers never redirects to “/”, in fact it does nothing.

I don’t want to POST the info using html forms, I am almost sure that this has to do with the http request I am sending but I don’t know what I am doing wrong, thanks in advance.


This line sends and XHR request with the ‘POST’ method.

xhr.open("POST", "/addTokens");

You hit these lines on your sever:

print("Redirecting to index")
return redirect(url_for('index'))

So you send a redirect response back, however, you don’t deal with it in your JS. (Klaus D bet me to it, but XHR don’t do redirects).

You then do a ‘GET’ request back to /addTokens

window.location.href = "/addTokens"

Which is why you never get back to your index.

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .