0

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)

2
  • if you want to send data without reloading web page then you have to learn AJAX - there is no other option. Commented Dec 9, 2020 at 14:58
  • button has to be inside <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 also type="submit" - without this it may not know if it should submit or reset data in form. Commented Dec 9, 2020 at 15:00

2 Answers 2

1

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

1 Comment

Although I marked @fullfine answer as the accepted this one helped me a lot too (specially the AJAX example, as I am considering using it). Thank you.
0

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>

Comments

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.