Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload a div via AJAX immediately and then every 5 seconds

I want to reload a div every 5 seconds. For this I found a script online which works. The only issue is that the first load of the file is after 5 seconds, but I want to first one to be immediately. It's probably a minor thing but I have never worked with Javascript before. Thank you!

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    function autoRefresh_div() {
        $("#div").load("load.html");
    }
    setInterval('autoRefresh_div()', 5000);
</script>
like image 252
Dr. Who Avatar asked Feb 01 '16 22:02

Dr. Who


People also ask

How do you refresh a page every 5 seconds?

setTimeout(function () { location. reload(1); }, 5000);

How do I load a div after Ajax success?

Just run inspect div after the method is completed. To avoid this issue use the following code: $("#divid"). load(" #divid > *");

How do I reload a div without reloading the whole page?

Use this. $('#mydiv'). load(document. URL + ' #mydiv');


1 Answers

You need to setup the interval timer and then call the function directly. Try this:

function autoRefresh_div() {
    $("#div").load("load.html");
}
setInterval(autoRefresh_div, 5000); // every 5 seconds
autoRefresh_div(); // on load

Also note that it's better practice to chain the requests using setTimeout(), rather than queue them. This is because if the server slows, or gets bogged down in requests you won't keep piling them on, as the next request only fires after the previous one completes. Try this:

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

autoRefresh_div();
like image 78
Rory McCrossan Avatar answered Nov 03 '22 00:11

Rory McCrossan