AleMal
AleMal

Reputation: 2077

Cache the results from the ajax calls to prevent running them multiple times

In my project i have a php file that launch a js function that make an ajax call. My problem is, if a user refresh php page on browser function re-make ajax call and so on. I need to cache the first result of ajax execution so that if the refresh is done being used data in the cache and not the ajax call is made again.

My call is

if (xmlHttp)
    {
    // try to connect to the server
    try
    {
      xmlHttp.open("GET", "top10.php?P1="+oStxt, true);
      xmlHttp.onreadystatechange = handleRequestStateChange10;
      xmlHttp.send(null);
    }
        // display the error in case of failure
        catch (e)
    {
        alert("Can't connect to server:\n" + e.toString());
    }

How can i prevent multiple ajax call from browser page refresh?

Thanks in advance

Upvotes: 0

Views: 175

Answers (1)

Tarwin Stroh-Spijer
Tarwin Stroh-Spijer

Reputation: 353

I would suggest the following flow:

  • Before making the request hash your request URL (MD5?)
  • Check to see if your localStorage (or similar) has a value for this hash
  • If no value
    • do your request
    • save returned data in localStorage with hash as key
    • render page
  • If value
    • load from localStorage
    • render page

Easy!

Upvotes: 1

Related Questions