One AJAX Pitfall Demoed with jQuery Mockjax

This blog briefly outlines one Ajax pitfall that can lead to inconsistency between user input and the rendered ajax response. I encountered this problem when developing a network management application where user can click a network node from browser then to see its statistical data. In the application, clicking a node would highlight the node and fire an Ajax call to fetch the device status data. Then the data is rendered once browser receives the response. At the end, it is expected to see the staticstics matching the highlighted node. However things sometimes can go wrong due to the asynchronization nature of the Ajax.

To illustrate the problem, I here wrote a very simple web page that contains a on/off switch. When the switch is pressed, an Ajax call is fired to fetch the data related to this state.  You can simply download the files and open the index.html file in a browser and quickly click the switch a few times. You will notice you may end up in a state where the switch is “ON” but the server says “OFF”.
onoff

This is caused by unpredictable delay from the network or server when fulfilling the asynchronization request illustrated by the diagram below.

ajax

In the diagram, the Ajax requests are dispatched in sequence when the widget is clicked thanks to the single threaded javascript on browser. However you can not control the network traffic policies as an application programmer so the request fired earlier may hit the server late. Even if the server receives the request in sequence, there is no guarantee which request can be fulfilled first due to server’s thread pool model, inter-process calling or caching availability, etc. If the earlier request is returned to the browser late, the inconsistency problem will occur.

To void of such problems, you should carefully design your UI and ajax invocations. Depending on your application, you may also include some request information in the response so UI can decide how to render the response by checking the embedded request information.

In the demo code, the ajax handlers are simulated by using jQuery MockJax and the onoff switch code can be found here.

Advertisements
This entry was posted in Javascript & html, Programming and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s