Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AJAX for auto refresh a div or a web page

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!

like image 479
gedamial Avatar asked Nov 23 '14 14:11

gedamial


People also ask

How do I make a div auto refresh?

Use window. setInterval() to Refresh a div in JavaScript.

How do I refresh a page in AJAX?

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.

Does an AJAX request refresh the page?

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 .

How do I automatically refresh part of an HTML page?

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.


2 Answers

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

like image 168
charlietfl Avatar answered Sep 24 '22 03:09

charlietfl


you can write some stuff like

var doSth = function () {

  var $md = $("#my_div");
  // Do something here
};
setInterval(doSth, 1000);//1000 is miliseconds
like image 28
Kenny Tai Huynh Avatar answered Sep 24 '22 03:09

Kenny Tai Huynh