Reputation: 23
I have a simple javascript function that executes when a button is clicked and I want to send some data from that function to the Flask backend.
My initial idea was this:
function sendDataToBacked() {
data = "I want to send this to backend"
document.getElementById("myButton").value = data;
}
I set the button value to 'data' and then with a form I send that value to the backend like this.
<form id="myForm" method="POST"></form>
<button form="myForm" id="myButton" name="button" onclick="sendDataToBacked()">Send</button>
And finally the python backend would look like this:
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
print(request.form['button'])
return render_template("index.html")
But it doesnt work :( Any idea how I can achieve this with pure javascript? (I know you can do it with AJAX)
Upvotes: 0
Views: 2830
Reputation: 143098
<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
Upvotes: 1
Reputation: 1461
I have written an example with two buttons, the first one makes the submit itself and send the data to the backend, the second one calls a function and it makes the submit.
I have used list(request.form.keys())[0]
to identify which button is making the submit.
Backend:
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if list(request.form.keys())[0] == 'button':
print(request.form['button'])
if list(request.form.keys())[0] == 'button2':
print(request.form['button2'])
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
Frontend:
<form action="" method="post" id='myForm'>
<button name="button" value="value">Send</button>
</form>
<form action="" method="post" id='myForm2'>
<button id="myButton2" name="button2" value=0 onclick="modifyData()">Send</button>
</form>
<script>
function modifyData() {
data = "I want to send this to backend"
document.getElementById("myButton2").value = data;
}
</script>
Upvotes: 0