I've been trying to do this for a lot of time, but I can't. Here is my problem: I have a web page just like this:
<html>
<body>
<div id="my_div">
<span id="txt">HELLO WORLD</span>
</div>
</body>
</html>
Now I want that the div "my_div" refreshes itself every X seconds, also refreshing its content. How to do this using AJAX or JQUERY or JAVASCRIPT?
Pay attention: I don't require a script that refreshes the entire page. Pay attention(2): I've just tried to find something by Google, but I found nothing.
Please, help me. I have been having this problem for many time.
Thank you in advance!
Use window. setInterval() to Refresh a div in JavaScript.
You can use the location. reload() method to reload or refresh an entire web page or just the content inside an element. The . reload() method can be triggered either explicitly (with a button click) or automatically.
Ajax request and Refresh event both will be happening at the same time even though its triggered one after another. Responce from the refresh event will disconnect all the http request for the session and load the fresh page. Also the server where the ajax is being made will check the client connection periodically .
Approach 1: One can auto refresh the webpage using the meta tag within the head element of your HTML using the http-equiv property. It is an inbuilt property with HTML 5. One can further add the time period of the refresh using the content attribute within the Meta tag.
Using jQuery load()
and an interval timer is about the simplest.
setInterval(function(){
$('#my_div').load('/path/to/server/source');
}, 2000) /* time in milliseconds (ie 2 seconds)*/
load()
is a shorthand method for $.ajax
This assumes that you would set up a server side script that only outputs the content for that element.
You could also use a selector fragment within load
url to parse a full page for the specific content
See load() API Docs
you can write some stuff like
var doSth = function () {
var $md = $("#my_div");
// Do something here
};
setInterval(doSth, 1000);//1000 is miliseconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With