Search code examples
javascriptpythonflaskserver-sideflask-wtforms

How to send confirm "ok" / ""cancel" from JS to Flask


I am trying to find a means to "collect" the input from the user, say if the user presses "OK" in a JS confirm window, I want to receive a "True" in python's flask, and "False" if users presses "Cancel".

I have this part for the JS function:

<script>
    function confirmBooking(elem) {
        if(confirm('Are you sure you want to book this slot?') == true) {
            //elem = 1;
            alert("its done: " + elem);            
        }
        else { 
            return 0;
        }          
    }
</script>

Now on "form" side I have this:

<form method="post"> 
     <button type="submit" name="free_button" value="free_button" onClick="confirmBooking('{{ booking_slot }}')"> Free </button> 
</form>

So, here, booking_slot is a python variable containing some string. I would like some means to set a True/False value to a variable in the Flask side if the user selects "OK" or "cancel" respectively.

Any way to achieve this? Thanks.


Solution

  • You need to create a function that will collect or fetch the input from your frontend to the backend. I usually do this technique.

    <form action="{{url_for('/collect')}}" method="post"> 
         <input type="hidden" id="userInput" name="userInput"> 
         <button type="submit" name="free_button" value="free_button" onClick="confirmBooking('{{ booking_slot }}')"> Free </button> 
    </form>

    <script>
        function confirmBooking(elem) {
            if(confirm('Are you sure you want to book this slot?') == true) {
                //elem = 1;
                alert("its done: " + elem); 
                document.getElementById("userInput").value = "True";
            }
            else { 
                 document.getElementById("userInput").value = "False";
                 return 0;
            }          
        }
    </script>

    @app.route('/collect',methods=["POST"])
    def collect():
        if request.method =="POST":
            userInput = request.form.get("userInput")
        return render_template('<template here>',userInput=userInput)