0

I'm writing a Google Chrome extension that uses a jQuery.post() call to send data to an external website. The external website handles the data using a Flask endpoint and generates a result. Unfortunately I am not sure how to transfer the result back to the client. How can I do this?

I've tried using a render_template call within Flask, like so:

app.route("/my_endpoint", methods = ['POST'])
def my_endpoint():
    print ('hi')  # this statement prints
    results = ...
    if request.method == 'POST':
        # want to eventually replace this with
        # return render_template("results.html", results=results)
        return render_template("test.html")

But this doesn't actually load the page test.html.

I've also tried transferring the data back to the Chrome extension using a callback (which I would prefer not to do if possible), as in

post_results = function(input_data) {
    jQuery.post("my_flask_endpoint",
        input_data,
        function (data, textStatus, jqXHR) {
            ...
        }

But I'm not sure what to put in the callback function, because it seems like "data" is a bunch of HTML, and I don't know how to load pages given only an HTML string (as opposed to the URL).

Jessica
  • 2,335
  • 2
  • 23
  • 36

1 Answers1

1

It's good that data is a bunch of HTML, because that's exactly what you sent it! render_template is the Jinja2 function you use to show a given page to a user, and in the end, all that is is HTML. What you are doing is returning the HTML rendering of test.html as the data.

What (I think) you are trying to do, is either return the "results" object, or trigger a redirect to /results after POSTing to /my_endpoint?

Depending on what you plan to do with the data, you could go either way.

If you are wanting to return the data to the users current page/the jQuery callback, try just returning results as JSON (assuming results is a dictionary). A more detailed explanation of jsonify can be found here

return flask.jsonify(**results)

Alternatively, if you plan to navigate to a different page to show the results, you need to decide whether you want Flask to perform the redirection and render the data using results.html as a template, or pass the results to the client and have it navigate and transfer the received data itself.

J.B
  • 1,642
  • 2
  • 15
  • 33