jQuery - do I really have an AJAX cache problem?


I don't often write about code - I am no coder - but I struggled with something for the best part of a day and I thought I would post this just in case someone at some point might find it useful.

I stumbled across jQuery after finding YUI just a little to big for me to get my mind around and I am glad I did because it seems simple enough for me to grasp. Anyway, I was using .load to call a SUB PAGE into a MAIN PAGE using AJAX. My set of routines that  something like this

  1.  MAIN PAGE calls SUB PAGE via .load. SUB PAGE has table for data entry and hyperlinks for kicking off SQL PAGE to execute relevant sql
  2. Following data entry into SUB PAGE (via MAIN PAGE), click on hyperlink updates database using SQL PAGE and then refreshes MAIN PAGE div that contains SUB PAGE

Well ... for hours I kept inputting data, then clicking the relevant links only to find that the MAIN PAGE div sometimes refreshed, sometimes didn't. F5 always worked though. So I was pretty sure I had a cache problem. So I stopped using .load and started using .ajax, using the 'cache: false'. I could see that .ajax was now suitably randomising the get url, yet still my MAIN PAGE div was not refreshing. I was certain I had a caching problem ...

But I did not.


Using Google Chrome's development tools - I could see that sometime my jQuery routine was doing exactly what it was supposed to do, i.e.

a) Click SUB PAGE; execute SQL PAGE; refresh MAIN PAGE div

And sometimes things happened in this order ...

b) Click SUB PAGE; refresh MAIN PAGE div; execute SQL PAGE

My code was written to do a), but because SQL PAGE took a while to execute, b) was actually what was happening. And b) was bad - my MAIN PAGE div was actually refreshing, but the SQL to update my data tables was not executing prior to the refresh.

Once I realised this, the fix was easy. Using .ajax, I implemented the following logic:

i) Click SUB PAGE
ii) Execute SQL PAGE
iii) Conditional on the successful execution of the SQL PAGE (using the 'success:' option in .ajax), then refresh MAIN PAGE div containing SUB PAGE
iv) I left the 'cache: false' in place, just in case

This fix works 100% of the time for my code

So if you are pulling your hair out trying to work out why caching won't turn off, just make sure that you actually have a caching problem and not the problem I have described above.

Good luck