3

I'm having trouble getting Flask to add text to an HTML page after a POST request. The POST returns a 200 code indicating that it went through and I see it in the terminal when the button is clicked. Additionally, I see the request.data printed when the button is clicked so it appears that the python code enters the if statement for the 'POST' request but it never renders the template with the result text. Any ideas?

HTML:

<button onclick="do_ajax()">Do Ajax</button>
<p>{{result}}</p>

JavaScript:

function do_ajax() {
  var req = new XMLHttpRequest();
  req.open("POST", "/index/", true);
  var blob = new Blob(['abc123'], {type: 'text/plain'});
  req.send(blob);
}

Flask/ Python:

@app.route('/<string:index>/', methods=['GET','POST'])
def my_form_post(index):
  if request.method == 'POST':
    print request.data
    return render_template('%s.html' % index, result = "It's working!")
  elif request.method == 'GET':
    return render_template('%s.html' % index)
  • You should [take a look here](https://stackoverflow.com/questions/47372745/flask-response-to-a-post-confusing-behaviour), not a straight answer to your question, but should help you understand where the problem is. – bgse Apr 17 '18 at 20:04

1 Answers1

1

You're sending the request, but you're not really doing anything after sending the request on your client side. You should render the response flask is sending you back on the client side. Note, normally you don't use ajax to render an entire page, but use the values send back by your server to fill in something in an existing element on the page, using the JSON format.

Here is a snippet that should get you going:

<h2 onclick="do_ajax()"> click here</h2>
<script>
function do_ajax() {
  var req = new XMLHttpRequest();
  req.onreadystatechange = function() {
    if (req.status == 200) {
        alert(req.responseText);
    }else{
        alert(req.status);
    }
  };
  req.open("POST", "/index/", true);
  var blob = new Blob(['abc123'], {type: 'text/plain'});
  req.send(blob);
}
<script>
Joost
  • 3,609
  • 2
  • 12
  • 29