AJAX with jQuery

    JSON itself is a very lightweight transport format, very similar to how Python primitives (numbers, strings, dicts and lists) look like which is widely supported and very easy to parse. It became popular a few years ago and quickly replaced XML as transport format in web applications.

    In order to use jQuery, you have to download it first and place it in the static folder of your application and then ensure it’s loaded. Ideally you have a layout template that is used for all pages where you just have to add a script statement to the bottom of your to load jQuery:

    Another method is using Google’s AJAX Libraries API to load jQuery:

    In this case you have to put jQuery into your static folder as a fallback, but it will first try to load it directly from Google. This has the advantage that your website will probably load faster for users if they went to at least one other website before using the same jQuery version from Google because it will already be in the browser cache.

    A simple method would be to add a script tag to our page that sets a global variable to the prefix to the root of the application. Something like this:

    Now let’s create a server side function that accepts two URL arguments of numbers which should be added together and then sent back to the application in a JSON object. This is a really ridiculous example and is something you usually would do on the client side alone, but a simple example that shows how you would use jQuery and Flask nonetheless:

    As you can see I also added an index method here that renders a template. This template will load jQuery as above and have a little form where we can add two numbers and a link to trigger the function on the server side.

    Note that we are using the method here which will never fail. If the key is missing a default value (here ) is returned. Furthermore it can convert values to a specific type (like in our case int). This is especially handy for code that is triggered by a script (APIs, JavaScript etc.) because you don’t need special error reporting in that case.

    I won’t go into detail here about how jQuery works, just a very quick explanation of the little bit of code above:

    1. $(function() { ... }) specifies code that should run once the browser is done loading the basic parts of the page.

    2. element.bind('event', func) specifies a function that should run when the user clicked on the element. If that function returns false, the default behavior will not kick in (in this case, navigate to the # URL).

    Check out the example source for a full application demonstrating the code on this page, as well as the same thing using and fetch.