How to use AJAX to automatically update a div or webpage
I tried to do this for a long time, but I cannot. Here is my problem: I have a web page like this:
<html>
<body>
<div id="my_div">
<span id="txt">HELLO WORLD</span>
</div>
</body>
</html>
Now I want the div "my_div" to update every X seconds, also updating its content. How can I do this with AJAX or JQUERY or JAVASCRIPT?
Please note, I do not require a script that refreshes the entire page. Please note (2): I was just trying to search for something from google but couldn't find anything.
Please help me. I've had this problem many times.
Thank you in advance!
source to share
Using jQuery load()
and the timer interval is the easiest.
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 you have configured a server-side script that only outputs content for that element. You can also use selector snippet in load
url to parse full page for specific content
See load () API docs
source to share
Using jQuery, you can dynamically update the content of an element using:
$("#my_div").html("... new content ...");
The new content replaces the original content.
Using the setInterval () method, you can force JavaScript to execute every period:
For example:
window.setInterval(function() {
$("#my_div").html("... new content ...");
}, 1000);
Will replace content every second.
source to share