Issue
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)
Solution
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>
Answered By - fullfine
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.