jQuery with Flask Tutorial

In this Flask web development tutorial, we're going to cover how to incorporate jQuery with our Flask application. The idea for this is to create a more interactive web application. With jQuery, you will be able to allow for elements and parts of your web page to be changed, in accordance with backend processes, without needing to actually refresh the web page.

Allowing for asynchronous loading like this gives you quite a few gains. Immersion, interactivity, and ease of use all go up. Furthermore, speed is improved. Instead of everything needing to reload, just a specific element reloads/loads. Let's consider a simple example, where we ask the user what the best programming language is. If they answer "python," then they are obviously correct and we'll display on the screen they are wise. If they answer anything else, we'll prompt them to try again. Regardless of what they type, and the answer, we want to keep the page from reloading, and just use jQuery to make the magic happen.

To start, we begin in our __init__.py file.

def interactive():
	return render_template('interactive.html')

Nothing too impressive yet. Typical function that returns a template. Let's make the interactive.html file next:

{% extends "header.html" %}
{% block body %}
		<div class='container'>
		<h3>Welcome! Which is the best programming language of them all?</h3>
				<input type=text size=5 name=proglang>
				<a href=# id=process_input><button class='btn btn-default'>Submit</button></a>
		<p id=result></p>
{% endblock %}

Here, we have some html that creates a short text input field, has a submit button, and a result. Notice the id=result and the id=process_input. These ideas are to be used in some javascript. We'll put this javascript in the head of this same file, like so:

{% extends "header.html" %}
{% block body %}
		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
		<script type=text/javascript>
			$(function() {
			  $('a#process_input').bind('click', function() {
				$.getJSON('/background_process', {
				  proglang: $('input[name="proglang"]').val(),
				}, function(data) {
				return false;
		<div class='container'>
		<h3>Welcome! Which is the best programming language of them all?</h3>
				<input type=text size=5 name=proglang>
				<a href=# id=process_input><button class='btn btn-default'>Submit</button></a>
		<p id=result></p>
{% endblock %}

Now, this isn't a javascript tutorial, but we can break this down anyway. We're creating a function, with the id of process_input, which is bound by a click for running (since we put the submit button in a form, we can just press enter too), and this function then visits the URL /background_process, which then grabs the json response from it, giving the proglang var (which is sent to the URL it is visiting and grabbing the JSON from) the value of whatever was put in the text box. After this, the result is populated with the data.result, which is the result part of the json that is returned. We could return multiple values in the JSON. For example we might also pack an image. To help understand that, let's actually create the fucntion for /background_process.

from flask import jsonify

#...other code...

def background_process():
		lang = request.args.get('proglang', 0, type=str)
		if lang.lower() == 'python':
			return jsonify(result='You are wise')
			return jsonify(result='Try again.')
	except Exception as e:
		return str(e)

So, here's a page meant to not really be visited by the public. All it does is return a json, based on user input. As you can see, if the user types in Python or python, they are claimed to be wise. Otherwise, they are told to try again. Should there be any sort of error, we're returning an error, but we could also return a json to try again, when in production.

Now, you can visit /interactive/, and then try out your new product! Try typing something, pressing submit or enter, and see what happens. You should be greeted with the response you created, and the page should not reload. If you see nothing, you are probably getting an error. Press F12 if you are in chrome, and you can read the script error if there is one. Alternatively, you can actually visit /background_process, appending a value, like /background_process?proglang=python. From here, you should be returned a JSON, like:

  "result": "You are wise"

If not, read the error, since we're outputing the errors. Pretty cool! Now, you can have jQuery operations running for whatever you like, returning all sorts of things. With this, you can actually create web pages that are only a single, interactive, page. Pretty neat!

That's all for now, in the next tutorial we're going to discuss Pygal. Pygal is an SVG plotting library, which is extremely simple, yet also very impressively powerful for making quick interactive embeddable graphs with Python and Flask.

The next tutorial:

  • Introduction to Practical Flask
  • Basic Flask Website tutorial
  • Flask with Bootstrap and Jinja Templating
  • Starting our Website home page with Flask Tutorial
  • Improving the Home Page Flask Tutorial
  • Finishing the Home Page Flask Tutorial
  • Dynamic User Dashboard Flask Tutorial
  • Content Management Beginnings Flask Tutorial
  • Error Handling with Flask Tutorial
  • Flask Flash function Tutorial
  • Users with Flask intro Tutorial
  • Handling POST and GET Requests with Flask Tutorial
  • Creating MySQL database and table Flask Tutorial
  • Connecting to MySQL database with MySQLdb Flask Tutorial
  • User Registration Form Flask Tutorial
  • Flask Registration Code Tutorial
  • Finishing User Registration Flask Tutorial
  • Password Hashing with Flask Tutorial
  • Flask User Login System Tutorial
  • Decorators - Login_Required pages Flask Tutorial
  • Dynamic user-based content Flask Tutorial
  • More on Content Management Flask Tutorial
  • Flask CMS Concluded Flask Tutorial
  • The Crontab Flask Tutorial
  • Flask SEO Tutorial
  • Flask Includes Tutorial
  • Jinja Templating Tutorial
  • Flask URL Converters Tutorial
  • Flask-Mail Tutorial for email with Flask
  • Return Files with Flask send_file Tutorial
  • Protected Directories with Flask Tutorial
  • jQuery with Flask Tutorial
  • Pygal SVG graphs with Flask Tutorial
  • PayPal with Flask Web Development Tutorial
  • Securing your Flask website with SSL for HTTPS using Lets Encrypt