Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Flask form submission without Page Reload

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Python3




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

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>

 
 

  • e.preventDefault() :-  This function doesn’t reload the page
  • type: GET or POST request
  • url : url that we have specify in our flask app
  • data : Form data that we want to pass
  • Succes: function() :- This function run after successfully submitting the values and when there are no error occur while submitting the data.

 

OUTPUT :-

 

 

 

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

 


My Personal Notes arrow_drop_up
Last Updated : 17 Jun, 2021
Like Article
Save Article
Similar Reads
Related Tutorials