Open In App

Flask form submission without Page Reload

There are many modules or frameworks which allows to build your webpage using python like bottle, django, flask etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you the versatility to program with.

Problem:



If we do post request then the whole page will reload. So this article revolves around how to send the form data to flask backend without reloading the page. For submitting form without reloading  page we use jquery and ajax. So before using flask we have to install that

Ubuntu



pip3 install flask

Create new directory for your project. Inside that create new file and name it as app.py

app.py




from flask import Flask,render_template,request
 
app = Flask(__name__)
 
 
@app.route("/",methods=["POST","GET"])
def home():
    if request.method == "POST":
        todo = request.form.get("todo")
        print(todo)
    return render_template('home.html')
 
 
if __name__ == '__main__':
    app.run(debug=True)
    

Then create new directory and name it as templates

Inside that create new file and name it as home.html

home.html




<!DOCTYPE html>
<html>
<head>
    <title>GFG</title>
</head>
<body>
  <form method="post" id="todo-form">
        <input type="text" name="todo" id="todo">
        <button type="submit">submit</button>
    </form>
 
        <!--Jquery Cdn -->
          integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
          crossorigin="anonymous"></script>
 
  <script type="text/javascript">
    $(document).on('submit','#todo-form',function(e)
                   {
      console.log('hello');
      e.preventDefault();
      $.ajax({
        type:'POST',
        url:'/',
        data:{
          todo:$("#todo").val()
        },
        success:function()
        {
          alert('saved');
        }
      })
    });
  </script>
 
</body>
</html>

 
 

 

OUTPUT :-

 

 

 

On the cmd or terminal it will print the value we have submitted using form.

 


Article Tags :