-1

I'm coding an app where there is a timer coded in Javascript. Here is my Javascript :

var time=5;
var display = document.getElementById("display");
display.innerHTML=time;

function timing() {
    if (time>0) {
        time--;
        display.innerHTML=time;
        $.ajax({
            url:"/c_cesar",
            type:"POST",
            contentType: "application/json",
            data: JSON.stringify(time)});
    }
    else clearInterval(timer);
}

var timer=setInterval(timing, 1000);

I'm sending the time variable through ajax to be able to collect the data in Flask :

@app.route('/c_cesar', methods=['GET','POST'])
def c_cesar():
    time=request.get_json()
    print(time)
    if time==0:
        print("time is up")
        return redirect(url_for('index'))
    return render_template('c_cesar.html')

The problem is that when time is 0, I would like to redirect the user to the index page. That is why I'm using an if statement. When time is 0, the message "time is up" is printed on the console, but the user is not redirected. This is what my console displays :

4
127.0.0.1 - - [06/Apr/2022 10:52:45] "POST /c_cesar HTTP/1.1" 200 -
3
127.0.0.1 - - [06/Apr/2022 10:52:46] "POST /c_cesar HTTP/1.1" 200 -
2
127.0.0.1 - - [06/Apr/2022 10:52:47] "POST /c_cesar HTTP/1.1" 200 -
1
127.0.0.1 - - [06/Apr/2022 10:52:48] "POST /c_cesar HTTP/1.1" 200 -
0
127.0.0.1 - - [06/Apr/2022 10:52:49] "POST /c_cesar HTTP/1.1" 302 -
127.0.0.1 - - [06/Apr/2022 10:52:49] "GET / HTTP/1.1" 200 -

How can I redirect the user ?

1 Answers1

0

The JS code gets executed in the browser.

When you make the ajax call a call to your flask background is made, that will in turn do a redirect. But the redirect will be for the POST request you made via $.ajax.

That will not redirect the users' browser session.

You need to move your if condition on the client side or read the response from your back end end do a client side redirect then.

You must run some JS script for this to happen. Most likely using window.location will work for this.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34