Python Flask jQuery Ajax POST

Python Flask jQuery Ajax POST

I have already covered an introductory article on getting started with python web application development using Python Flask and MySQL. In this Python Flask jQuery AJAX tutorial, we’ll focus on the client side of the web application. We’ll see how to use jQuery AJAX along with Python Flask web application.

Prior to getting started with this tutorial, make sure you have Python installed. You can check if it’s installed from the command prompt:


python --version

If python is installed, it’ll show the version of python installed.
We’ll use pip to install Flask. Setting up Flask using pip is quite easy.


pip install Flask

Why Python Flask jQuery AJAX ?

Why do we need to use jQuery AJAX along with a python web application ? When creating a web application it’s often needed to pass in the data from client side to the server side methods to get response from the server. jQuery is just one simple way to achieve this. You can also use other client side libraries or frameworks like AngularJS to POST data to the python web application.

Python Flask Web Application

Create a app directory called FlaskApp, navigate to it and create app.py with the following code:


from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Welcome to Python Flask!"
 
if __name__ == "__main__":
    app.run()

The python code shown above is quite self explanatory.

First we imported the Flask module and then created a flask app instance. We have also defined a hello function with a route defined as / .

Save the app.py and from terminal run:


python app.py

Your app must be now running. Point your browser to http://127.0.0.1:5000/ and you should see the welcome message.

Let’s create a Sign Up page called signUp,html. We’ll be using Bootstrap to power our html files. Here is how signUp.htmllooks like:

<!DOCTYPE html>
 <html lang="en">
 
 <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <meta name="description" content="">
     <meta name="author" content="">
     <link rel="icon" href="../../favicon.ico">
 
     <title>Signin Template for Bootstrap </title>
 
     <!-- Bootstrap core CSS -->
     <link href="static/css/bootstrap.min.css" rel="stylesheet">
 
     <!-- Custom styles for this template -->
     <link href="static/css/signin.css" rel="stylesheet">
 
     <script src="static/js/jquery-1.9.0.js"> </script>
 
 </head>
 
 <body>
 
     <div class="container">
 
         <form class="form-signin" action="/signUp" method="post" role="form">
             <h2 class="form-signin-heading">Please Sign Up </h2>
             <input type="email" name="username" class="form-control" placeholder="Email address" required autofocus>
             <input type="password" name="password" class="form-control" placeholder="Password" required>
 
             <button class="btn btn-lg btn-primary btn-block" type="button">Register </button>
         </form>
      
     </div>
   
 </body>
 
 </html>

Next add a method called signUp on the python side to handle the request and render the corresponding html file. We have used the render_template to display the signUp page on a /signUp request. All we need to do is import render_templateand return the rendered template as response. Here is how it looks like


from flask import render_template
 
@app.route('/signUp')
def signUp():
    return render_template('signUp.html')

Using Python Flask jQuery AJAX Together

Now we’ll use jQuery AJAX to post the form data to the Python Flask method. Create a new JavaScript file called script.jsand include it after jQuery in signUp.html.

We’ll attach a click event on button click and call python method using jQuery AJAX. Here is how the script.js looks like:


$(function() {
    $('button').click(function() {
        $.ajax({
            url: '/signUpUser',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});

In the above code we have simple serialized the form data using $form.serialize() and posted it to the python web method. Now add a python method called signUpUser to receive the data from client side. Here is how it looks like:


@app.route('/signUpUser', methods=['POST'])
def signUpUser():
    user =  request.form['username'];
    password = request.form['password'];
    return json.dumps({'status':'OK','user':user,'pass':password});

We have explicitly defined the method that it supports using the methods attribute. In order to retrieve the posted parameters we have made use of the request module. We have also used json module to return json data to the client side. json.dumps returns the json to client side.
Now restart the server and point your browser to http://localhost:5000/ and try to sign up. Check browser console to see the returned json data. So, python flask jQuery AJAX is up and running 🙂

Wrapping It Up

In this Python Flask jQuery AJAX tutorial, we saw how to post data using jQuery AJAX to a python web application. Do let us know your thoughts, suggestions or corrections in the comments below.

Read : How to Read Email From Gmail Using Python

The code from the above tutorial is available in GitHub.

20 thoughts on “Python Flask jQuery Ajax POST

  1. I want to pass the selected value from drop down to a python script through an AJAX call. Please help. Please tell me if i have to share the code

      1. I saw your tutorial and understood the concepts, but what i am trying to achieve is as follows:

        I want to pass the selected value from dropdown which contains names of
        databases and pass it to the python script in the background which connects to the
        passed database name. Following is the ajax code that i have written

        $(document).ready(function(){
        $(“button”).click(function(){
        $.ajax({
        url : “/form_submit”,
        data : $(‘#databases’).val(),
        type : ‘POST’,
        success : alert(“Hi dear count ” + $(‘#databases’).val())
        });
        });
        });

        The
        “databases” is the id of the select tag in HTML. I am writing data
        : $(‘#databases’).val()
        to pass the data to the python code.

        Following is the python code which should accept the passed value.

        @app.route(“/form_submit/”, methods=[‘GET’,’POST’])
        def connect():
        import json
        dtb = request.select[‘value’]
        db = MySQLdb.connect(“localhost”,”root”,””,dtb)
        cursor =
        db.cursor()
        cursor.execute(“SELECT * FROM REPORT_SUITE”)
        results = cursor.fetchall()
        json_return_value =[]
        for result in results:
        table_data = {‘REPORTSUITE_ID’ : result[0], ‘REPORTSUITE_NAME’ : result[1], ‘STAGING_DATABASE’ : result[2], ‘DWH_DATABASE’ : result[3], ‘TRANS_TABLE’ : result[4]}
        json_return_value.append(table_data)
        print (“hi”)
        print json.dumps(json_return_value)
        return json.dumps(json_return_value)

        I have declared the variable as dtb = request.select[‘value’] which should accept the database name
        passed through AJAX call. Also i should be able to see the returned data in JSON format in my web browser.

        I have looked around and applied many suggested solutions but i still am unable
        to determine how to pass and catch the passed value.

        I also tried this

        request.form[‘value’] but it says global name ‘form’ is not defined

        I think the code i am writing to call python function and pass the value to it is not correct and
        also the variable in python program(dtb) which should accept the value is also not correct.

        1. Hey @sonalkhare:disqus Sorry for the late reply. I would recommend you fork the source code and make changes as required. From the code that you have posted a couple of things are missing like the imports.

  2. You should mention that Flask expects to find the signUp.html file in a ‘templates’ directory: otherwise, you get a 404.

  3. Hi,
    I need to send my coordinates from the image( which I get from clicking on the image in JS) to the server and finally to the database. How can I do this using Flask and $.ajax()?

  4. Hi, I need some help please, i’m using python – flask – template method
    i need to display a word in HTML interface without refreshing the page ?????

  5. Hi, I need some help please,how to fetch data in mysql query without refreshing page in django using angularjs.

  6. Hi – In your click event, you try to get the username and password values from the form using #txtUsername and #txtPassword, but these ids don’t appear on the form fields so those values will be null. Also, you don’t actually pass these into the ajax request so these values aren’t used for anything – makes sense to either get rid of them or use them for some client-side validation before you hit the ajax request instead.

Leave a Reply

Your email address will not be published. Required fields are marked *