jQuery with Flask - Flask Web Development with Python 32

sentdex · Beginner ·🔧 Backend Engineering ·10y ago

Key Takeaways

The video demonstrates how to incorporate jQuery with Flask to create interactive web applications, utilizing tools like JSONify, Bootstrap, and PYAL for graphing and asynchronous operations.

Full Transcript

What's going on everybody? Welcome to another Flask web development tutorial video. In this video, what we're going to be talking about is the marriage between Flask and jQuery. So, the idea of jQuery is to be able to have asynchronous operations happening without forcing a reload of the entire page. So what this allows us to do is like only update certain elements on the page based on maybe user input or even a user action that took place. And what this kind of gives us is is two major benefits. One is better loading times. So obviously it's better to reload or load a specific portion of a web page rather than having to reload the entire web page. Also, these operations can happen in the background and not actually um force the user to do nothing. So, if you're on a page and maybe certain assets are waiting to load, but other ones are ready to go, you might as well show the page what's ready to go and then whatever is loading, you could even display like a loading bar or, you know, something like that. But it at least it's better than just a white screen and a little loading icon for the tab, right? So, it makes your web pages a little more interactive or a lot more interactive depending on how how you're using it and then also either a little faster or a lot faster again depending on how you use it. So, let's go ahead and get started uh with just a nice simple example. So, let's open up init.py here. And what we're going to do is we're going to be using JSONify. This is something that comes with Flask. And with JSONify, you put a variable and a and a value basically. And when you JSONify a bunch of variables and values, it just converts it to a nice JSON format, uh, which is JavaScript object notation. And it's a lot like a dictionary, and we treat it a lot like a dictionary. So anyways, we're going to import JSONify here. Again, that's coming from Flask. All this stuff is coming from Flask. So, uh, now just find a good spot to make a new page. I'm going to search for Ginger Man here. And I'm going to also just copy that. Make some space here. paste. And we're going to call this page interactive. We're also going to call the function interactive. And we're going to delete this stuff and that. And we're going to make this interactive.html. Okay. So now let's go over to our templates and we need to make interactive.html. So new file and inter interactive.html. So once we have that uh basically we are going to let me pull up 404 and just grab at least this part and this part. Great. And then within these body tags, we're going to just have some div tags. And uh we're going to have this will be a fairly simple page. Basically, what this page is going to do is um within the div, we're just going to have it ask ask the user a question. And then the question is going to be uh which is the best programming language of them all and to which the user must answer. We're going to give them a nice input form. The type will be text. The size will be five. The name will be Prague lang. So this is the name of the variable. Uh and the value will be whatever the user actually puts into this text input. Subsequently we need some way for that user to submit the data. So we'll have a button class equals uh btn btn default. So that's that bootstrap default button there. And uh we'll do button. And in here, we'll just say submit. Okay. And then finally, to make this button actually do something, we'll just say href uh pound sign. Just a stereotypical stereotypical that's the right word, but the typical uh method to make a button clickable yet not actually go anywhere is to use the pound sign. So, we do that. And then also what we're going to do is we're going to give an ID equals uh process input. What that's going to do is it gives this button an ID of process input and that's going to allow us to tie that button ID to a JavaScript function which will do some cool stuff for us here in a moment. So after all that we're going to come down here uh P and P and actually before we go there let's make well I think we'll make that function. Now, one thing to note is let's save that and let's go over here and reload and let me pull up this page for us. Do this. Whoops. Uh, we're going to head to the interactive page. And here's what they're looking at. Basically, it's, you know, what is the best programming language of them all? They might be stupid. Maybe they put Java. And you'll notice that if you if you hit the I'm hitting the enter key. You can't see me, but you'll take my word for it. The enter key is not doing anything. But if I hit submit, sure enough, it works. The way that we can make the inter uh the enter key actually work here in this case would be to enase this in a form. So form, and we'll just tab this over and that'll be enough to actually make the enter key do something. So let's go back to this page and then say it said Java. Hit enter. You'll see it's actually assigning that that value and stuff. So, it actually does perform an action for us. Now, we're not actually looking to do anything with this page and assign this value to this page, but you can see that it worked with the enter key. So, just keep that in mind. So, now what we need to do is we want to make this actual the function here that runs. Now, as usual, this tutorial is posted on pythonprogramming.net. So, for the fun uh for the JavaScript function that we're about to write, uh just head there and grab the function. It's not really JavaScript tutorial, but also that it would just take a long time for me to write, but I will at least explain to you the JavaScript function that we're running. So, uh you can head there, grab it, and uh just basically copy and paste it in like that. So, what's happening here is uh within the head tag, we have this this script. Actually, we've got two scripts. The first script is jQuery coming from Google API. Uh you can kind of do one of two things here or actually a few but um you can either host a jQuery the script like you can host this literal script just like we're hosting bootstrap scripts you can host it locally if you want but sometimes it can be a lot better to use something like Google because Google is like a CDN which is a content delivery network. So Google has multiple servers around the world. So this is a bunch of uh script. It's a bunch of code that has to be returned to that user so they can load it. Uh so if you're if you're using the source of this script to be Google, chances are their server for the major chances are Google's going to have a server closer to the majority of your users than you do unless you have a content delivery network. Uh so that's why people will host remotely. Um just yeah. So anyways, that's what we're doing for jQuery. Next, we have our own little local script here. And this script is bound by here, right? So this is our process input. So that's this right here. So the based on the click here when the a user submits based on this ID, we're going to pop up here. And what are we doing? Well, we're binding based on a click or the enter key because we put it into a form based on a click a function. What's it going to do? Well, it's going to get the JSON returned basically from this URL from our website. That URL does not exist. We have to create it. When it visits that URL, what we want to do is we want to say Prague lang is the input that the user did whatever that was programming language. So we're saying proglang this is JSON saying hey the value for the variable proglang is going to be equal to the val. So the value of whatever the user put in to proglang which was down here right this input okay proglang it submits that to here right and uh the return is what we're calling a result the return is the text value of data result again we're returning a JSON from this URL so data result data is the whole JSON Result is you can think of this just like a dictionary. Result is the key. So the value is this right? So in theory you could also envision it like this like it's a dictionary. Also dictionaries do support the dots. So now what we need to do is first of all result this is what like basically result is going to be the ID right if you haven't noticed yet. So this is your your ID of process input. This is your ID of result. So now what we could do is in these paragraph tags we can say id equals and we can say the ID of this paragraph tag is result. So now whatever the result is will be populated between these paragraph tags. So you could put something first like you could put dot dot dot right to start. So when nothing is there dot dot dot will be shown but then whenever there's a new value for results it will replace the dot dot dot. But for now, we'll just leave it empty. So, uh, we have everything we need now except for this background process. So, let's go ahead and add that background process. Um, let me just close these. Hopefully, none was open. Uh, back here init. And let's go ahead and search for that ginger man again. Ginger man. Again, don't forget to make sure you've imported uh jsonify gingeran heading there. And in fact, let me show you one thing before uh we move on. So whenever you're working with JavaScript, JavaScript and especially like what we're doing here is again it's asynchronous. So it is going to experience graceful degradation. So what that means is again with by default with Python and Flask and what we've been doing so far, if any bit along the way, you think of it like a chain, right? If any little bit along the way breaks, the whole thing falls apart, right? Everything is worthless. But with graceful degradation, doing things asynchronously, it's think of it more like a rope. If a certain if one fiber of that rope breaks, the rope's weaker, but the the rope still will do some work for you. So keep that in mind. So when we go over here uh and we load up our interactive page, let's do a hard refresh here. and the user goes to type something like um let's say they say Java, they hit enter, nothing's happening. Okay, we'll click submit. Ah, nothing's still happening. Well, on Chrome, you can open up the dev tools with F12 and you can see, woo, we've got eight errors. All eight errors are probably us hitting enter a bunch of times. But we can see here right away failed to load this resource. I don't think I can zoom Oh, I can zoom that in. Look at that. Uh, it failed to load. I can zoom it in, but it's like all huge mess this URL. So, it's failing on the background process. We can even click that and we can see, oh, that page is corresponding with a 404. Of course, that's because it doesn't exist. But if you had an error on this page, you'd click this page and you'd find, oh, it's a maybe a 500 error that we're getting. So, uh, keep in mind that if things aren't working right, go ahead and go to the dev tools and basically you're looking for this like this little error, right? and then you click on that and you it you'll find the errors, but because it's asynchronous, it's everything else is going to be just fine. So, sometimes that can kind of mask problems. And if you're using JavaScript a lot, especially like jQuery and stuff, you're going to want to go ahead and see uh just press F12 from time to time and see all the stuff that's broken on your website. If you go to a lot of major websites, too, you'll see how much JavaScript is broken a lot. It just that just happens. So these things just break. So anyway, um we need to make that page now. So what did I do with the in here? It is. Uh bring this down. And uh here's our interactive page. Now we need to make that other page. So let's just take this copy paste. And this page is uh background_process. Now, generally when people make processes that or even functions that are used only by other functions, they use an underscore uh to lead that function. It's just like a notation that hey, this is not something for everyone else. So, you can do that if you'd like. I'm not really going to worry about that for now, but just keep that in mind. So, now we make this background process, and we'll call this background process. And what background process wants to do is uh it's going to try to get the language. So the language was remember that prog line. So to get that we just do request.orgs.get and we're looking for that variable that corresponds to prog. Okay. And then what we're going to say is if lang actually let's let's make it string. If string len what if they put like a five or something we're treating like an int or something could go wrong there. if string lang. lower to kind of normalize it. So just in case they put a capital J for Java or lowercase J or capital P for Python or whatever if string.Lower is equal to uh Python. We're going to return to the user uh we're going to return JSONify. And then in here you just put keys and values. Okay? So you say result equals because remember we're looking for that result value. Uh result equals uh you are you are wise uh else we return JSONify JSON 50 result equals uh try again right so anything else they type in we're just saying uh try again so we'll save that and don't confuse result here with the ID of result that we're returning. Okay, so that result is really the result here corresponds to the result here, not the result here and not the result here. The result here corresponds to this result where we're actually just assigning the value of this data result. Okay, so uh that's should be everything we need. So let's go ahead and pop back over here. Let's save. Close that. Save that. Move this over. Uh move this over. Let's reload Apache. And uh let's go ahead and uh let's go just refresh. And I'm going to do a hard refresh here. Shift F5 in Chrome just to make sure. And let's type in Java. Hit enter. And it says try again. Okay. So then we could do like Python. Hit enter. And it says you are wise. And you should notice that the page never reloaded. It just simply loaded this tiny element right in here, right? And we can F12 and see that sure enough, nothing nothing went wrong. We didn't have any errors or anything like that. So cool. So anyways, um obviously a really basic example, but you can start to see how you could make a lot of elements updated basic based on using jQuery uh and calling background tasks to run return some data and return the page values and stuff like that. So anyways, uh if you have any questions or comments on uh using Flask and jQuery, uh feel free to leave them below. In the next tutorial, what we're going to be talking about is PYAL, which is an SVG uh graphing library that you can very very easily embed into your Flask applications. It makes for pretty nicel looking graphs. They are slightly interactive graphs. Basically, you can hover over them and get values and stuff. Um, they're good-looking, highly customizable and super simple, which is a really rare combination. Uh, and they have a ton of different types of graphs like lines and bars and piraphphs and maps and all kinds of stuff. So, anyways, that's what we'll be talking about in the next tutorial. So, stay tuned for that. Otherwise, thanks for watching.

Original Description

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. Text-based tutorial and sample code: https://pythonprogramming.net/jquery-flask-tutorial/ http://pythonprogramming.net https://twitter.com/sentdex
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

This video teaches how to use jQuery with Flask to create interactive web applications, covering topics like asynchronous operations, JSONify, and graphing libraries. By following the steps and using the mentioned tools, viewers can create their own interactive web pages.

Key Takeaways
  1. Open up init.py and import JSONify from Flask
  2. Create a new page called interactive with a function called interactive
  3. Assign an ID to a button and bind a function to a click or enter key event
  4. Create a URL to return JSON data from a Flask website
  5. Use the dev tools to debug JavaScript errors and find the source of the problem
💡 Using jQuery with Flask allows for the creation of interactive web applications, and understanding asynchronous programming is crucial for handling errors and creating background processes.

Related Reads

📰
7 Apache Kafka Design Patterns Every Backend Engineer Should Know
Learn 7 essential Apache Kafka design patterns for building scalable and efficient real-time data streaming systems
Medium · Programming
📰
Symfony Validator: Where Framework Validation Ends, Domain Rules Begin
Learn to separate framework validation from domain rules in Symfony to avoid duplicating logic and improve code maintainability
Dev.to · Gabriel Anhaia
📰
Seu status de pedido não devia ser uma string
Learn how to replace status strings with Enums in PHP 8.1 to improve code quality and prevent bugs
Dev.to · Denis Augusto
📰
From a Go CLI to a full developer ecosystem: Gopher Glide for IDEs
Learn how to transition from a Go CLI to a full developer ecosystem using Gopher Glide for IDEs, enhancing your backend development workflow
Dev.to · Shiyam
Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →