AJAX Feed Ticker Widget

Jobs from Indeed
Published:
By:

JAXFeedTicker is a web site widget that creates a ticker on your website with items from remote feeds that you select in an administration page. The widget utilizes many advanced scripting techniques that we will discuss below and these techniques can be viewed in the demo here and in the source code that you can download here. There are similar widgets available for purchase here.


Dynamically Loading Javascript

The widget relies on the jQuery Javascript library so it must wait for this library to be loaded before the widget executes and if the page in question does not currently utilize the jQuery library then the widget must load the library itself.

This is accomplished through an initialization script (jaxfeedticker/jaxfeedticker_init.js) that waits until the page document has finished loading and then checks for the existence of the jQuery object. If the object is not found then the initialization script will load the jQuery library before continuing.

// wait for document load to complete
var readyStateCheckInterval = setInterval(function() {
  if (document.readyState === "complete") {
    // clear the check interval
    clearInterval(readyStateCheckInterval);

    // check to see if the jQuery library is loaded
    if (typeof jQuery == 'undefined') {
      // create a script element to load the jQuery library
      jqueryScriptTag = document.createElement('script');
      jqueryScriptTag.type = 'text/javascript';
      jqueryScriptTag.src = jquerySRCURL; // using jQuery library source from settings

      // append new script element to document body to start settings load process
      document.body.appendChild(jqueryScriptTag);
    }

  } // end of document readstate == complete check
}, 10); // end of readyStateCheckInterval

An interval is set up to execute every 10 milliseconds and check the readState value of the page document. If the document is not ready then it waits another 10 milliseconds. If the document is ready then the next check is to determine if the jQuery object exists. If jQuery does not exist then a script tag is created and appended to the document to load the jQuery library dynamically.

When you examine the entire initialization script in the downloadable source code you will see other examples of dynamic loading including the CSS stylesheet used to theme the widget.

Passing Javascript Functions as Callbacks

A common and useful practice in Javascript is to pass a function as a parameter to be used as a callback when the primary function finishes. The jaxfeedticker jQuery plugin in the package does just this when it makes an AJAX request for feed items from the server.

$.fn.jaxfeedticker.ajaxRequest('getFeedItems', {}, function(data) {
  // update feed items if provided
  if (data.feedItems) {
    tickerItems = data.feedItems;
  }

  // update seconds between ticker refresh if provided
  if (data.secondsBetweenTickerRefresh) {
    settings.secondsBetweenTickerRefresh = data.secondsBetweenTickerRefresh;
  }

  // reset count down
  getFeedCountDownMS = settings.secondsBetweenTickerRefresh > 0 ? 1000 * settings.secondsBetweenTickerRefresh : -1;
});

In the jQuery plugin there is a call to the ajaxRequest() function where the last parameter is a function. The function is to be called when the AJAX request finishes and it passes the requested feed items to this callback function for processing.

In the ajaxRequest() function itself we can see that on success there is a check to see if the callback parameter is set and if it is set then it is called as a function and passed the data from the AJAX request.

// function to make an AJAX request
$.fn.jaxfeedticker.ajaxRequest = function (action, ajaxData, callback) {
  // combine ajax data and action request
  $.extend(ajaxData, {'ajaxAction': action});

  $.ajax({
    url: settings.AJAXURL, //'AJAXRequest.php',
    data: ajaxData,
    dataType: "json",
    success: function (data, status) {
      if( callback ) {
        callback(data);
      }
    },
    error: function (data, status, e) {
      // AJAX failure

    }
  });
};

Storing Data in JSON Format

The widget may be making multiple remote calls for feed data for every page hit on the web server. This could rapidly overload the server and place an unnecessary load on the remote servers that provide the feeds. So the widget stores the feed information temporarily in cache files using JSON format.

While the entire process is too complicated to go into detail we can see in the jaxfeedticker/AJAXRequest.php message handler where a JSONFile object is created to store feed results in a cache file and then followed up with a call to write an associative array to the JSON file.

$cacheFile = new JSONFile('cache/' . $uuid . '.cache');
$cacheFile->writeJSONFile(array(
  'timestamp' => time(),
  'feedItems' => $newItems
));
This will create a cache file that contains a JSON formatted object representing the associative array that was passed to the writeJSONFile() function call. If you dig further into the JSONFile object code you will find that the PHP json_encode() function is called on this associative array before it is written to the cache file.

public function writeJSONFile($data, $filename = NULL) {
  // use this source filename if not provided
  if (empty($filename)) $filename = $this->filename;

  // save the JSON data to the file
  return $this->lockedWrite($this->filename, json_encode($data));
}

Demo, Source Code and More

There is a great deal more that can be learned from the code in action and having access to the source code itself. You can view a demo on getwebscripts.com here and you can download the source code here. The techniques used in this widget are also implemented in other widgets that can be purchased from my profile here.