How to tips and tricks for Microsoft Visual Studio .net

Friday, April 19, 2013

jQuery ajax().load caches url

In my mind, the jQuery ajax().load functionality is possibly one of the best things about jQuery.

I ran into a problem that drove me nuts for a little while...

I have a div:

<div id="divStatus"></div>

I wanted to load some html into it each time I show a popup that contains it, like this:

  // Page Variables
  var ParsedURL;
  var port;
  var BaseUrl = "";

  $(function () {
    var url = document.URL;
    ParsedURL = parseUri(url);

    port = ParsedURL.port;
    if (port != "") {
      port = ":" + port;
    }

    ShowStatusesDDL();
    ReadAndDisplayCookieData();
  });

  function ShowStatusesDDL() {
    // Build the Base URL
    BaseUrl = ParsedURL.protocol + "://" + ParsedURL.host + port + ParsedURL.directory;
  
    // Add the rest of the text to the url for the BuildStatusDropDownList Handler
    var LoadUrl = BaseUrl + "WebHandlers/BuildStatusDropDownList.ashx?t=" + ParsedURL.queryKey["t"] + "&id=" + ParsedURL.queryKey["id"];

    $('#divStatus').load(LoadUrl);
  } 
The problem with this code, is that every time the .load method runs, the url is the same. The .load method caches the url, and if it isn't different each time the .load method runs, it will return the cached return values.

To fix this you need to make the url unique every time it runs, like this:
  // Page Variables
  var ParsedURL;
  var port;
  var BaseUrl = "";

  $(function () {
    var url = document.URL;
    ParsedURL = parseUri(url);

    port = ParsedURL.port;
    if (port != "") {
      port = ":" + port;
    }

    ShowStatusesDDL();
    ReadAndDisplayCookieData();
  });

  function ShowStatusesDDL() {
    // Build the Base URL
    BaseUrl = ParsedURL.protocol + "://" + ParsedURL.host + port + ParsedURL.directory;

    // Build a Globally Unique Identifier to add to the url to make it unique every time it is loaded -
    // This is because jQuery.load caches the url and won't re-load it each time unless the url is different
    var RandomGuid = guid();

    // Add the rest of the text to the url for the BuildStatusDropDownList Handler
    var LoadUrl = BaseUrl + "WebHandlers/BuildStatusDropDownList.ashx?t=" + ParsedURL.queryKey["t"] + "&id=" + ParsedURL.queryKey["id"] + "&guid=" + RandomGuid;

    $('#divStatus').load(LoadUrl);
  } 

  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
  }
Pretty basic, but if you don't know about the .load method caching, it will confise the hell out of you.

No comments:

Post a Comment