Freakin’ AJAX call won’t pull the latest data

By | July 23, 2012

Was working on this really simple website at my job the other day. Since it was so simple, I decided to make the “data” area of the site a simple XML file that I’d just update and re-push out to the site to update data behind listboxes, etc. No big deal.

Or so I thought.

Turns out the following:

    if (window.XMLHttpRequest) {
        requestor = new XMLHttpRequest();
    }
    else {
        requestor = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    requestor.
    
    requestor.open("GET", "data/Pricing.xml", false);
    requestor.send();
    pricingXml = requestor.responseXML;

Is good until you change Pricing.xml. Since the request has been made once before recently, the server’s cached the value of the response (the XML file data) and gives back to you what it cached, NOT what you updated.

Grr.

So I did some Binging and came back w/ a pretty ingenious way of getting around this:

    requestor.open("GET", "data/Pricing.xml?" + new Date().getTime(), false);   // getTime used to get unique request, so it's not cached by the server
    requestor.send();
    pricingXml = requestor.responseXML;

See what I did there? It makes the URL that’s requested be unique every second, but still requests the Pricing.xml file so the data’s not changing. Just slap on an ever-changing URL parameter (that’s never used) and you’re golden. Pretty sweet.

I also found a couple of other things that you *should* do to implement this “correctly,” but from what I’ve seen, the above method works just fine. That is, I haven’t found an instance where I’m getting back cached data.
Yet.

  • Joe

    Adding a client-side hack to fix a server-side bug. Good choice!

    • Brandon

      i’m not sure it’s a server side bug, per se.. as the it’s just caching responses as it should. If i’d have gone a full-blown “right” implementation this data would be behind a service that would return non-cached responses and the problem wouldn’t exist.

      • Joe

        The server bug is that it’s emitting headers indicating the content can be cached. Look at the response headers in Fiddler to see what I mean. To fix this I recommend using the NoCacheAttribute solution from
        http://stackoverflow.com/questions/1160105/asp-net-mvc-disable-browser-cache

        • Brandon

          ah very nice. good tip! How does that translate to JS, though? this was a JS call I had to get hacky with