<button> has to be inside <form></form> to send it.
<form method="POST">
<button id="myButton" name="button" onclick="sendDataToBacked()">Send</button>
</form>
If you want to send other values then you have to also put them inside <form></form>
You may have many forms on the same page and every form need own button to send it - so form have to know which button belong to form.
Minimal working example
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
print(request.form)
return render_template_string('''
<script>
function sendDataToBacked() {
data = "I want to send this to backend";
document.getElementById("myButton").value = data;
}
</script>
<form method="POST">
<button id="myButton" name="button" onclick="sendDataToBacked()">Send</button>
</form>
''')
app.run()
but this code will also reload page. If you want to send it without reloading then you will have to learn AJAX.
EDIT: the same with AJAX using modern method fetch instead of older XMLHttpRequest or external library jQuery
from flask import Flask, request, render_template_string, jsonify
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
print(request.form)
return render_template_string('''
<script>
function sendDataToBackendAjax(event) {
// create own form in memory
const formData = new FormData();
// set values in this form
formData.append("button", "I want to send this to backend");
fetch("/ajax", {
method: "POST",
body: formData
//headers: {'Content-Type': 'application/json'},
//body: JSON.stringify(formData)
})
.then(function(response){
data = response.json(); // get result from server as JSON
//alert(data);
return data;
})
.then(function(data){
alert(data.info);
console.log(data);
})
.catch((error) => {
console.error('Error:', error);
});
event.preventDefault(); // don't send in normal way and don't reload page
}
</script>
<form method="POST" action="/ajax">
<button id="myButton" name="button" onclick="sendDataToBackendAjax(event)">Send Ajax</button>
</form>
''')
@app.route('/ajax', methods=['GET', 'POST'])
def ajax():
print(request.form)
return jsonify({'result': 'OK', 'info': 'Hello World!'}) # send result to browser as JSON
app.run() #debug=True
<form></form>but you have it outside<form></form>and form will not send it and you can't get it in Flask -<form> <button></button> </form>. I'm not sure but button may need alsotype="submit"- without this it may not know if it should submit or reset data in form.