Reputation: 33
I have the simplest flask app:
app = Flask(__name__)
@app.route('/python/', methods = ['GET','POST'])
def index():
return "Hello World"
if __name__ == "__main__":
app.run(debug=True)
and a very simple webpage with a text area and a button.
<textarea id="mytextarea">Some text...</textarea>
<p> Click the button </p>
<button type="button" onclick="myFunction()"> Click here</button>
<p id="demo"> </p>
What I want to do is to put the response from Flask on the webpage using a script when the button is clicked. I tried the following but it doesn't work. Nothing happens when I click the button. What am I doing wrong?
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:5000/python/", true);
xhttp.send();
var x = xttp.response;
document.getElementById("demo").innerHTML = x;
}
</script>
(I am a beginner).
Upvotes: 3
Views: 3060
Reputation: 351
see the code below and review the XMLHttpRequest.onreadystatechange for detail
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "http://127.0.0.1:5000/python/", true);
xhttp.send();
}
</script>
no cors issue if you send the html from your flask app see the example code, you need to import render_template from flask.
@app.route('/')
def hello_world():
return render_template('index.html')
Upvotes: 2