Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing an AJAX POST followed by GET with Flask

My goal here is to have the user fill out a form, send that information in a POST request to the flask server, then render a template using that form information (after it undergoes some logic on the server).

So far, I have completed the POST part of all of this. I am trying to render a template right now inside the if request.method == POST', and I guess that's not working right now.

Here's the code I have so far:

@app.route('/filteredsearch/', methods = ["GET", "POST"])
def filteredsearch():
    if request.method == 'POST':
        data = json.loads(request.data)
        tables = data['checkboxes']
        filter_results = getFilteredEntities(tables = tables)
        print filter_results                          #This works
        return render_template("filteredsearch.html", entities = filter_results)

Do I have to do a separate GET request on the success of my POST function? If so, how would I do that?

Here is the AJAX request (if it matters, this code can be called on every single page of the app):

$.ajax({
              url:"/filteredsearch/",
              type: 'POST',
              data: json,
              contentType: 'application/json;charset=UTF-8',
              success: function() {
                           alert("Done");
                       }
          });

So, ideally I can render a template while I'm posting. If that's not the case, how do I go about doing a GET request from the same ajax function?

I know that typically you use url_for() for a GET request, is that an option given that I'm in JS at this point?

like image 500
Alex Chumbley Avatar asked Nov 25 '13 22:11

Alex Chumbley


People also ask

Does AJAX use Get or POST?

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option.

Can you use AJAX with flask?

In this article, I will show how to use AJAX with Flask, a Python framework, to receive and display the values entered in a form asynchronously. I added the source code that we need at the end of the article.

How GET and POST method are used in AJAX?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

Is it possible to make POST request in flask?

Flask POST request is defined as an HTTP protocol method that enables users to send HTML form data to server. The HTTP protocol is the foundation of data communication and is basically defined as an application layer for collaborative, distributed, hypermedia information systems.


2 Answers

Normally you use an ajax request to return data that you then dynamically display in the page.

$.ajax({
    url:"/filteredsearch/",
        type: 'POST',
        data: json,
        contentType: 'application/json;charset=UTF-8',
        success: function(evt) {
            $("#results").html = evt.data;
        }
}); 

If you are going to redirect to another template then why not just click submit on a form that makes a POST and then responds with the new template. If you actually want to redirect to a whole new page after the ajax request has come back (which is going to be slower than just displaying the information you've already received) then you could change the window.location. Something like window.location = 'http://www.example.com' would take the user to example.com.

like image 166
aychedee Avatar answered Oct 21 '22 15:10

aychedee


I know it's a little late, but i just had the same problem than you.

I needed to make a POST with Ajax and then if it succeeded I needed to make a GET request to flask to return a rendered template. Something like:

FLASK PART:

@app.route('/something', methods=['POST'])
def something_post():
    # Get JSON object passed with Ajax request
    elems = request.json
    # Do stuff
    # If everithing is OK, return success message
    return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}

@app.route('/something', methods=['GET'])
def something_get():
    # Return template
    return render_template('something.html')

AJAX PART:

$.ajax({
        type: 'POST',
        data: myJsonString, // JASON object passed to flask
        url: '/something',
        contentType: "application/json",
        method: 'POST',
        success: function(response) {
            # If we succed we make a request to get the template
            window.location.href = "/something";
            # With this line we are making a simple GET request to Flask and the template returned is opened in the current window
        }
});

Please, note than I'm far, far away to be an Ajax expert. I don't know if this is the correct way to do it but it was the simplest way I found.

like image 29
bcedu Avatar answered Oct 21 '22 13:10

bcedu