Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
Like this article? We recommend

The Data Reflection Pattern

The data reflection pattern keeps the page content in sync with the database. It runs in the background and updates data that has changed while a user is using the application. As the standard model does, the data reflection pattern starts with the user interface, but the major difference is that it programmatically consists of JavaScript’s setTimeout method. This method continuously uses AJAX to call a server-side language and check for database updates. If there are updates, the new data is returned to the AJAX callback method and the page content is updated. The chart in Figure 2 shows the flow of this pattern.

Figure 2

Figure 2 Data reflection pattern.

The setTimeout is the key difference in this pattern; it creates the data reflection. Take a look at the code below to see how you can implement this method into the AJAX object that we created in the standard AJAX model:

this.dataReflection = function(_delay, _callbackMethod)
{
  setTimeout(_callbackMethod, _delay);
}

The dataReflection method accepts two parameters: the time delay in milliseconds, and the callback method that will be called when the data is received. Following is an example of how to make a request with the data reflection method:

function get()
{
  ajax.makeRequest(’POST’, ’services/post.php?method=get, onResponse);
  ajax.dataReflection(1000, get);
}

To reflect the data, the callback method will need a way of updating the (X)HTML with the new content, if the content has been updated. For instance, look at the following code and notice how the onResponse method checks whether the date for a specific post has been updated:

var _date = null;
function onResponse()
{
  if(ajax.checkReadyState() == "success")
  {
    var response = ajax.request.responseXML.documentElement;
    if(_date != response.getElementsByTagName(’date’)[0].firstChild.data)
    {
      // Add parsing code here
    }
  }
}

This makes the application run more efficiently because it eliminates unnecessary content updates.

The data that’s returned contains a date element with a server-side timestamp as its value. This pattern can be applied to a number of situations, such as statistics or data representations that need to be updated continually. The next pattern is an example of data reflection in a multiuser situation.

  • + Share This
  • 🔖 Save To Your Account