Home > other >  Javascript - ajax refreshing a div with an old version of an updated file
Javascript - ajax refreshing a div with an old version of an updated file

Time:04-20

I am making a web dashboard and for this I have a javascript function that loops infinitely, updating a particular div at frequent intervals. (it uses ajax/jquery to do this).

I have used a loop with setTimeout:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script type="text/javascript" language="javascript">

      function updateMain() {
        setTimeout(function() {
          console.log("updating");
          $('#main').load('new-content.php #main', function() {});
          updateMain();
        }, 3000)
      }

      updateMain();
    </script>
  </head>

  <body>
    <div id="main">
        <p>hi there</p>
    </div>
  </body>
  
</html>

'new-content.php' is a file that is constantly updated by another part of my program, to show the new content for the dashboard. it looks something like this:

<div id="main">
    <p>Hello i am updated content</p>
</div>

I am sure the loop is working as the "updating" messages appear at regular intervals in the console.

When the program starts, the div is showing "hello there", and in the new-content.php file it has "hello am updated content".

The first time the loop runs, it updates the div to show "hello i am updated content".

But if I further update the new-content.php file, for example to say "hello I am further updated content", it just won't show on my webpage. However I am sure that the loop is still running as the messages appear in console.

It's like ajax has some cached version of the new-content.php file that it loads at the start then keeps using forever.

I am very confused, if you could help me I would be very grateful

Thank you

PS: if it is of relevance, the website is running through flask but I don't think this is the problem.

EDIT: I believe it is actually a flask caching issue

CodePudding user response:

You can try adding a cache buster to see if that helps. Change your code as follows:

function updateMain() {
        setTimeout(function() {
          console.log("updating");
          const cb = new Date().getTime();
          $('#main').load('new-content.php?cb='   cb   '#main',function() {
           updateMain();
          });
          
        }, 3000)
      }
  updateMain();

CodePudding user response:

Wasn't able to solve the issue but for anyone who is trying to make a similar project, I decided to use flask-socketio instead which allows me to send data to javascript to be shown on the page, instead of javascript loading the data itself from a file. (the answer by vladtn on this SO post was useful as an introduction to socketio)

  • Related