0

I am building a project in which I take an image from the users webcam and return it to Flask as a base64 string via an AJAX call. However I want my users to be redirected after processing the image on the server side. I have tried using render_template() but it seems that render_template doesn't get executed at all. I also tried with redirect but that too didn't work. Below is the code which I am working on.

index.js

$.ajax({  
      type: 'POST',  
      url: '/upload',  
      data: {imagebase64: imagebase64data},  
  }).done(function (){  
    console.log(imagebase64data)  
  });  

main.py

@app.route('/success')
def success():
  return render_template('success.html')

@app.route('/fail')
def success():
  return render_template('fail.html')

@app.route('/upload', methods=['GET', 'POST'])
def get_image():
  img_ret = readb64()
  if(prev_img(img_ret)): #this function returns a boolean and based on that I have to redirect
      return redirect(url_for("success")) #this line has no effect
  else:
      return redirect(url_for("fail"))

Can anyone tell me what I am doing wrong? Or is there any way to redirect the user on a specific condition?

pythonista
  • 330
  • 4
  • 7

1 Answers1

0

Your AJAX function hits the server, the server performs the operation, and then the server responds with the outcome of redirect(...). Your AJAX call then receives that response, but doesn't do anything with it. In the first place, you probably don't want to receive the response generated by Flask's redirect in your AJAX call.

You have several options for what you can do to handle redirection. If you want to continue using AJAX, you'll want to return a JSON response from your /upload endpoint, containing some information usable in your AJAX request function in index.js indicating the success or failure of the upload. You can then use that information to redirect using window.location.replace(...) on the client-side. For an example of this see here.

Another option is to use an HTML form. This is straightforward to do with Flask and is also straight-forward to secure if you use a library like Flask-WTF. That will allow you to use the redirect functions from Flask, and make your AJAX call superfluous.

Mark
  • 41
  • 1
  • 2