3

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).

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

I figured out the problem. Cross Origin Resource Sharing was what I needed. Now it works. It works!!
@solitarywinter see the edit above if you are accessing it from your flask app no cros issue. But if you are accessing it from other server(for example port 80) then you will face cors issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.