user5242820
user5242820

Reputation:

Reload Div automaticly

I have a div on my .php site which contains some content. Now, I want the Div to refresh itself after every 5 seconds by a script on the same page.

I already tried to do this by JQuery, but all examples given just showed how to load and refresh content from another file.

Whats the most simple way to solve this? (Maybe with JS?)

At the Moment I'm struggeling with this:

function autoRefresh_div() {
  $("#div").load("load.html", function() {
    setTimeout(autoRefresh_div, 5000);
  });
}

autoRefresh_div();

Upvotes: 0

Views: 131

Answers (1)

Sampson
Sampson

Reputation: 268482

The approach you're taking should work, with a couple small changes:

// Look-up this element once; not for each request
let element = document.getElementById("div");

function autoRefresh_div() {
    // Add a selector to jQuery.fn.load
    $(element).load("load.html #div", function() {
        setTimeout(autoRefresh_div, 5000);
    });
}

autoRefresh_div();

One thing to keep in mind is that the $.fn.load method requests the entire document, which could be fairly large. It then discards all of this, saving only the element you wish to display. This is a bit wasteful, especially for users who have to watch their data usage.

If the element displays a value from your database, I'd encourage you to construct some primitive REST API that allows you to retrieve that value alone. You can then request it alone with any of jQuery's AJAX methods.

Upvotes: 1

Related Questions