How can I run a python flask function on the click of an html button WITHOUT going to a new page(app.route)?

44 Views Asked by At

I have tried finding videos and people with similar questions to mine but all either show how to redirect the user to a new page on the click of a button or get input from user on the click of a button, which is not what I want to do. I want to be able to show the user the letter "A" when he/she clicks the button. I am using python flask and html.

    <html>
      <head>
        <title>GradingGuru</title>
        <style>
          body {
            background-color: rgb(255, 251, 251);
          }
        </style>
      </head>
      <body>


        <div id="button"> 
          <button> add letter A </button> # Show letter "A" to user onClick w/python
        </div>

    from flask import Flask, render_template

app = Flask(__name__)



@app.route("/")
def home():
  return render_template('home.html')



if __name__ == "__main__":
  app.run(host = '0.0.0.0', debug = True)
1

There are 1 best solutions below

0
Carmelot On

A classic ajax, i think it would work for you:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $.ajax({
          url: "/add_letter",
          type: "POST",
          success: function(response){
            alert(response);
          },
          error: function(xhr, status, error){
            alert("An error occurred: " + error);
          }
        });
      });
    });
  </script>

You can add this script to your html, to head likely