You can use ajax
. First, in your template (named home.html
), create a script with jquery
:
<html>
<body>
<div id="connection" class="fp"> XX </div>
<button id="hit" type="button" name="">get text</button>
<div id='placeholder'></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$('#hit').click(function() {
var text = $('#connection').text();
$.ajax({
url: "/get_text",
type: "get",
data: {result:text},
success: function(response) {
$("#placeholder").html(response);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
When the button is clicked, the text from the div
element is captured and sent to the backend. However, the backend must return a response as well. To do that, create the route with flask
, and access the result returned by ajax
, and return some HTML:
@app.route('/')
def home():
return flask.render_template('home.html')
@app.route('/get_text')
def get_text():
returned_result = flask.request.args.get('result')
print(returned_result)
#do something with returned_result
return '<strong>Thanks!</strong>'
When I run the script, the result below is printed to the terminal:
XX