Python Ajax JSON Request Example: Form with Flask (2023)

Python Ajax JSON Request Example

Although this topic I am writing this article somewhat doesn’t match this domain of data science. But I found it useful for data scientist to build their own Flask APIs. As a data scientist, you may require to interact with Flask APIs with Python Ajax and JSON. This article contains steps by steps for building your APIs in Flask and interacting with Ajax in HTML form.

What is JSON?

JSON stands for Javascript Object Notations mostly used for data interchange. It is very easy for humans to read and write JSON. In the same way for machines like Computers, it can be easily parsed and generated. Calling it is very easy. JSON starts with the left Curly brace { and ends with the right curly brace. Inside the { }, there are two things one is the key name and its values. Below is an example of JSON Objects. It can also be the array of objects

{

"name": "John",

"age": " 26"

}

It can also be an array of objects. Like there can be more than two objects inside the array.  Below is an example.

{
"students":[

{
"name": "John",
"age": " 26"
},

{
"name": "Sahil",
"age": " 28"
}

]

}

How to request JSON with Python AJAX?

Let’s take a simple HTML file having two input fields. The user will enter the first name and last name and the data will be sent to the flask route as Post request and it will display the value of the field in the HTML. The following is the HTML code. I am using bootstrap also in the HTML, thus making the form input box look nice. If you want to know more about Bootstrap. You can read the documentation on the bootstrap.

Html Code For the form.

<form class="form-inline">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstName">First Name</label>
<input type="text" class="form-control" id="firstName" placeholder="First Name">
</div>
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" placeholder="Last Name">
</div>

<!--Submit Button-->
<button type="submit" class="btn btn-default">Submit</button>
</form>
</br>
<div id="output"></div>
</br>

We have made two input fields to be entered by the user. Firstname with the id ‘firstName‘  and Lastname with the id ‘ lastName‘. After entering the input field you will call the Ajax Javascript part that will finally display the combination of the values that is First Name and Last Name. It will display just after the submit button. Here it is a simple form. If you want to build and test it on your own form then you can make your with a nice style using bootstrap form.

Coding the AJAX Part

Ajax is a framework of Javascript. Now let’s understand the Html code. Ajax requires the following class and ids of the above HTML code for performing the functions.

  1. form – It is a class of the entire form.
  2. firstName – First Name id. It will be entered by the user.
  3. lastName – Last Name id. It will also enter by the user.
  4. submit – It is a type of button.
  5. output – It is an id where the combination of the first and last name will be shown here.

Now after reading the Ajax code, you will learn how the Ajax functions communicate with these classes and ids to perform the tasks.

First of keeping in mind that to run the entire Ajax part without any errors you have to include the main jquery part. You can add jquery from the Google-hosted libraries. At the writing, this post’s jquery version was 3.3.1.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

The code for the Ajax part is below.

$(document).ready(function() {
     $('form').on('submit', function(event) {
       $.ajax({
          data : {
             firstName : $('#firstName').val(),
             lastName: $('#lastName').val(),
                 },
             type : 'POST',
             url : '/process'
            })
        .done(function(data) {
          $('#output').text(data.output).show();
      });
      event.preventDefault();
      });
});

Explanation of the Above Code

Let’s understand the above code. $ is used to determine the variable.

The complete code will give the output without reloading the page. $(document).ready(function() { } ) tell the browser to run the functions after the document that is HTML is fully loaded. Inside the curly braces of the function, I called the form part $(‘form’) .on ( ‘submit’, function(event){  } );. This statement will search the entire HTML document for the ‘form‘ attribute and call the functions after clicking on submit which is the type of the button.

Inside the function even is the parameter for event.preventDefault(). It will prevent Jquery from doing the default action of the element for performing tasks. In the function, I have done the ajax part. $.ajax( { } ) Inside the curly braces of the ajax, fields values first name and last name is taken as a JSON object.  It will be like the following.

data: {

key1 : $(‘ attribute”).val,

key2 :$(‘ attribute”).val

}

Then you will define the request method which is POST or GET. Here I will use the POST method mean sending the data to the server. After that URL value. Here you will enter the URL for the flask POST method that will perform the tasks on JSON data. The statement .done(function(data) { }. All the things that are received from the URL part will perform tasks on the attributes of the HTML. You can think it will be the main output when the submit button is clicked. The $(‘#output’).text(data.output).show() will give the final output received by the called URL and show in the attribute output. Please Note that Here I am showing the only combination of the First Name and Last Name entered by the user.

Simple Steps to Rember the AJAX code

For beginners, It is difficult for the above Ajax part to remember. The following steps you should keep in mind.

Step - 1. Call the document load function.

$(document).ready(function() { 

            Step 2 : Call the action on submit evenet :  

            $('form') .on ( 'submit' , function(event){ 

                   Step 3:  Call the Ajax Function

                   $.ajax( {

                    Step 4: Create here the data for the field values. Request Method 'POST' OR 'GET' and Url for Processing the form.
						data : { 
						key1: $('attribute').val(),
						key2: $('attribute').val(),
						.
						.
						keyn: $('attribute').val()

						}
						type : 'POST' OR 'GET'
						url : '/example'

                   } ) 
				
				   Step 5: Call the success function. 

				   .done(function(data) {
                    
                      Step 6 : Wrtite the code for the data retured from the Server url: '/example'

				   });

				   Step 7 : Prevent the enitre submit event to do default action
                                   event.preventDefault();

            } );

} );

In the next section, You will learn how to do the URL part. We will use the Python web framework Flask. There will be posting the data and showing the output in the HTML attributes.

How to create endpoints in the Flask?

Flask is a Python web framework. It allows us to create endpoints and interact with forms and API easily.  I am here only doing the implementation part. If you want to learn more about Flask then read the Flask documentation. You can also find the Udemy Video courses for the Flask.

For interacting with the above HTML and JSON data, you are required to create a Post endpoints URL in the Flask Function. Also, you have to render the HTML file where the form is available in a different URL. It means you have to do the following two things.

  1. Rendering the HTML File.
  2. Create a route function for the URL /process.

Let’s understand step by step how you will create the functions.

Steps for creating the Flask app

Step 1: Import the following modules required for creating the Flask Function

from flask import Flask,request,render_template,jsonify

Flask is for creating endpoints URL Functions. The request is for telling the Function for GET or POST response. The render_template is for attaching or rendering the HTML file created. Jsonify is used to return or create the JSON response.

Step 2: In the next step, You will create an object of  Flask with any name lets take the app for this example.

app = Flask(__name__)

Step 3: Create a URL endpoint for rendering the above HTML file let’s say the name of the file is index.html.

The following is the code for creating endpoints and rendering the HTML file.

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

@app.route( ) is the Python decorator used to bind the URL for the specific functions. In the above code, @app.route(‘/’ ) binds the home page to the index() function. Inside the function, the statement return render_template(‘index.html’) returns the index.html to the browser.

Step 4: Create an endpoint for the form of the HTML page. The code for the process method is given below.

@app.route('/process',methods= ['POST'])
 def process():
  firstName = request.form['firstName']
  lastName = request.form['lastName']
  output = firstName + lastName
  if firstName and lastName:
   return jsonify({'output':'Full Name: ' + output})
return jsonify({'error' : 'Missing data!'})

The @app.route(‘/process’,methods= [‘POST’]) contains two parameters the URL field ‘/process’ and the request methods. Here we used the POST method for getting the form values. The request.form[‘firstName’] and request.form[‘lastName’] get the field values to return in the JSON format from Ajax.  The variable output = firstName + lastName will assign the Full name of the person.

The return jsonify( {‘output’:output} ) will return output as JSON data.

if __name__ == '__main__':
app.run(debug=True)

The statement if __name__ == ‘__main__’:  check whether the python code is in the same module or not. It means if all the required code is in the Python file or not and if it is then it will import all the modules from the same file. In the same way, app.run(debug=True) will run the Python app in debug mode. The following is the final image of the output

python ajax
Output

 

Conclusion

You may install flask python module for here.

Flask
Flask

Javascript is an object-oriented programming language. Its main task to create interactive effects for the browsers. Ajax is a framework of Javascript. You can think of it as an upper level of Javascript. JSON is a data format. It is mostly preferred by the large programming community as the data format. Python is a very popular language that’s why we have chosen Python web framework Flask for building the Python Ajax web page. In the article “Python Ajax JSON Request Example ” We have tried to make it simple for making it more interesting and knowledgeable.

If you want to learn in detail about Python Flask then the REST APIs with Flask and Python is the best Video Course on it. You can also refer to the below books on Python Flask.

Flask By Example

Building Web Applications with Flask

And If you have any queries and want to add any suggestions. Then contact us We will definitely help.

Other Scenarios

Deployment of Flask App

After the creation of endpoints in the flask, to use in live production, you have to deploy it on the server. There are many ways to do so. For example, you can deploy it on a free Heroku server. Also, you can deploy on your own server. To deploy You will use gunicorn with nginx to run the app smoothly. However, you can also use docker containers to run the app.

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner