Translate

Friday, June 15, 2012

AJAX - Browser History

One of the issues with using AJAX in a web site is that the browser history does not work. I spent a few days trying out quite a few of the solutions that you can find on the web and I was unable to find one that worked consistently in my application. The only option left was to add my own history and back button to my application.

The script file, rgUrlHistory.js:

var rgUrlStack = new Array();
var rgIdx = 0;

function rgPushAction(mAct, mApp, mID, mType) {
  rgObj = [];
  rgObj.action = mAct;
  rgObj.appID = mApp;
  rgObj.type = mType;
  rgObj.id = mID;
  rgUrlStack.push(rgObj);
  //limit to 10 items
  if (rgUrlStack.length > 10) rgUrlStack.splice(0,1); 
  rgIdx = rgUrlStack.length;
}

function rgBackAction() {
  var rgPop;
  //if we are at the top of the stack we need to pop this value because the first value popped is the current URL
  if (rgUrlStack.length == rgIdx) rgUrlStack.pop();
  //if we still have a value, pop it
  if(rgUrlStack.length > 0){
    rgPop = rgUrlStack.pop();
    //always keep one value on the stack
    if(rgUrlStack.length == 0) rgUrlStack.push(rgPop);
  }
  return rgPop;
}


In my application I call rgPushAction to save my URL and some additional information:

onclick="rgPushAction('%{urlFkey}','%{appTableID}','%{ID}','%{currentAppTable.type}');

On the menu bar in my web application I added a left arrow icon and call the the following JavaScript when the image is clicked:

function runBackQuery(){
   $.publish('HideViewMenu');
   var rgObj = rgBackAction();
   if(rgObj != ""){
     listView(rgObj.type, rgObj.appID, rgObj.id)
     $.post(rgObj.action, function(result){
          $("div#divBody").html(result);
        });
     $.publish('ShowDivBody');
   }
}

This script uses jQuery post with the URL we saved returned in rgObj.action to populate our target Div tag, divBody. "listView" is just another function that is called with the additional information we saved in the rgObj object. That's all there is to doing your own browser history for your AJAX actions.

No comments:

Post a Comment

Thank you for commenting!