Polling with JavaScript

To enable our messages to update automatically without a browser refresh, we will create two JavaScript functions—messagePoll, which will get the latest messages, and updateMessages, which will update the HTML with these new messages.

Start by replacing the Jinja2 if block in our home.html, which iterates through our list of messages, with the following line:

<div id="messageContainer"></div> 

This will be used later to hold our new list of messages generated by our jQuery function.

Inside the <script> tags in our home.html, write the following code:

function messagePoll() { $.ajax({ type: "GET", # ① url: "/messages", dataType: "json", success: function(data) { # ② updateMessages(data); }, timeout: 500, # ③ complete: ...

Get Python Programming Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.