Creating a responsive user interface – Updating browser data in real time using jQuery and ajax

The Application

Any sort of User Interface (UI) that displays data that changes in real time needs two main components: a request from the browser (client) to a server, and a response from the server with (hopefully) some data. Examples of this are ubiquitous, but good ones are things like device control panels with indicators as well as interactive widgets.  Core functionality:

  • The browser should be able to update itself based on predetermined conditions such as timeouts
  • The user should be able to interact with the interface by supplying or requesting data when they choose
  • Data is updated selectively, not requiring a browser refresh event

Below are a few examples we have kicking around here:

Control panel application with indicators and controls
Control panel application with indicators and controls
Mobile control panel application with neat widgets
reflow temperature profile
Real time data plotting

Why Asynchronous?

Getting data into your web page is simple. If you want to dynamically create a web page, you can use anything that will generate text: perl, python, php … the list is endless. Tell your web server how to interpret it, and it will happily serve it up for you. This doesn’t, however, give you content that updates itself. You have to refresh. Very web 1.0.

In most languages, the interpreter executes the command and resumes on the next line when the command is complete. To read a file in python, for example, you might do something like:

f = open('workfile', 'w')
mytext =
print('here is the entire file')

Because the program stops until the command is complete, it is blocking, or synchronous. This creates problems with interfaces, and especially if you were to use synchronous commands in a web interface. What if it takes 2 seconds for the server to respond and deliver your data? What if it is unavailable and times out? What if you have ten files you want to parse and update? What if you are retrieving 4,000 data points? Bad Things.

All of these situations will lead to at best sluggish response and a poor user experience. In the worst case, the browser will simply lock up and cease responding. These scenarios point to the need for asynchronous data requests. Enter Ajax. While the acronym stands for Asynchronous Javascript And XML, it’s very useful if we use Javascript Object Notation (JSON) to send data back and forth. While strictly speaking this is AJAJ, most still refer to this as Ajax, along with any interface code that facilitates sending data between client and server. It’s also possible to force it to be synchronous, but we won’t discuss that here.

The jQuery AJAX call

So how do we do this magic Ajax? Well, as the name implies, we need some javascript. Now, it is worth noting that it is possible to do your ajax using vanilla javascript, i.e. without jQuery, but why would you? jQuery takes the pain out of most javascript and just makes things better. If you need a primer on how to set it up and use it, take a look here. It’s as simple as a line in the head of your html documents to import the library and you are ready to start using the wonderful library of functions. I won’t spend time here explaining what jQuery is shortcutting  when it comes to ajax.

The docs for the jQuery.ajax() tell us what we need to know – send in a url and optionally some settings as a plain object and it will perform an asynchronous (override with async=false) http request. Here is a boiler-plate example, with explanations below the break. Remember that $ is a shortcut for jQuery function, so $.ajax() is the same as jQuery.ajax().

function showMeData(data) {
    var callback=showMeData;
    url: "/wsgisqlitequery",
    type: "post",
    data: {'database':'/data/database.db','table':'mytable'},
    success: function(response){
    // Execute our callback function

Now what does each of the options do?

url tells the query where to go for the data. In this case, ‘/wsgisqlitequery’ refers to the link wsgisqlitequery at the site root. In the site configuration, we’ve got an alias that tells our server where this actually goes. We’re using wsgi with an apache directive in our site definition:

WSGIScriptAlias /wsgisqlitequery /usr/lib/iicontrollibs/wsgi/wsgisqlitequery.wsgi

You could also use standard cgi-bin, in which case your url would be something like /cgi-bin/myscriptname with a directive like:

ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/

We’ll discuss the differences between these two approaches later.

type specifies whether we are issuing a POST or GET request. GET is the default, and here we choose POST for compatibility with our wsgi script server-side.

datatype specifies what datatype we are expecting back from the server. This will direct the client (browser) to parse the data as it is returned. We specify json here, which works beautifully for our wsgi script. We send our data back as a python dictionary (through a json dump), and it pops out as json objects, with keys as property names and the values as property values. In other words, if we return data and assign it to ‘myfundata’, and it’s a dictionary with key ‘myproperty’ and ‘mypropertyvalue’ as its value, if we were to follow our ajax query with:


We’d be greeted with an pop-up with ‘mypropertyvalue’. Magic!

callback specifies a function name that will be executed after the data is returned. Herein lies the beauty of the ajax request. We send it off, and when it’s completed successfully we do what we want with it. No interruption! We can even add additional parameters to the original request to feed into the callback. Say, for example, we want to see how long each query takes. We can send that on to the callback:

function showMeData(data,time) {
    console.log('Here is our data. It was returned in ' + time + ' ms')
function myajaxfunction(database,table,callback){
    var inittime=new Date();
        url: "/wsgisqlitequery",
        type: "post",
        data: {'database':database,'table':table},
        success: function(response){
        // Execute our callback function
            var finishtime=new Date();

Even better, what if we want to send a set of parameters into the callback, depending on what we’re doing? We can make this as flexible as we want:

function doStuffWithData(data,options) {
    // Here is the data

    // Here are all the options: how we got it,
    // and maybe what to do with it

function myajaxfunction(options){
        url: "/wsgisqlitequery",
        type: "post",
        data: {'database':options.database,'table':options.table},
        success: function(response){
        // Execute our callback function
var options = {'database':'/data/mydatabase.db','table':'mytable','callback':doStuffWithData}

Server-side response

Ok, now that we’ve sent our formatted request and are eagerly awaiting data, how do we process it on the server side? Here is some base code that will make this work. Now remember that wsgi is python-specific (it’s what django uses, for example), so the following is in python. This is the wsgi file that has been aliased as mentioned above in the apache site definition:

def application(environ, start_response):
    import cgi, json

    from mylib import myspecialfunction

    post_env = environ.copy()
    post_env['QUERY_STRING'] = ''
    post = cgi.FieldStorage(

    # Get the form data
    for k in post.keys():
        d[k] = post.getvalue(k)

    status = '200 OK'

    # Run stuff as requested
    if 'runspecialfunction' in d and 'myvariable' in d:
        if data['result']:

    output = json.dumps(data,indent=1)
    response_headers = [('Content-type', 'application/json')]
    return [output]

Now, without getting into too much detail, the main components of the script are pretty clear. We set the environment, retrieve the post form data, convert it to a dictionary, and process it as we see fit. When we’re done, we send it back to the client as a json dump! Pretty simple!

More on wsgi vs. cgi and processing your json on the client side when I return… in the meantime, check out how to get your ajax timing right.

4 thoughts on “Creating a responsive user interface – Updating browser data in real time using jQuery and ajax”

Leave a Reply

Your email address will not be published. Required fields are marked *