Doing an AJAX POST followed by GET with Flask
ajax, flask, jquery, python
Solution
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.
Problem
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?