Mulan
Mulan

Reputation: 135187

How to auto-refresh a page using ajax (and prevent an actual browser refresh)?

I am trying to append a small autofreshing javascript to a page that already has jQuery.

I don't have control of the site, so I can't add a simple script to the HTML that would appear after each refresh.

I have to run the script in the console otherwise the page will only refresh once.

Here's what I'm trying:

var x = function(){
  // reload the page
  jQuery('html').load(window.location.href);

  // recurse every 5 seconds
  setTimeout(x, 5000);
};

// init
x();

This is generating an appendChild error. I'm guessing I'm just going about this a bit wrong.

Upvotes: 0

Views: 10007

Answers (4)

Castilho
Castilho

Reputation: 3187

Maybe you want to replace the body with the contents of the page. It won't reload the whole page, so your script will stay right there. It could, however, conflict with existing scripts on the page.

How to do it:

var x = function () {
  $('body').load(window.location.pathname);

  setTimeout(x,5000);
}
x();

jQuery Reference

edit:

and now a more 'syntatically not so awful' approach: rewrite the whole document.

var x = function () {
  $.get(window.location.pathname, function (data) { 
    document.open(); 
    document.write(data); 
    document.close(); } 
  );

  setTimeout(x,5000);
}
x();

This works and do not reload the page under the body tag.

But I think is too much typing and worries for an injection hack :P

Upvotes: 1

Mulan
Mulan

Reputation: 135187

Despite the lack of belief that this is possible, this solution, while not perfect, is certainly working quite well

(function x(){
  jQuery('html').html('<iframe width="100%" height="' + $(window).height() + 'px" src="' + window.location.href + '"></iframe>');

  setTimeout(x, 5000);
})();

Upvotes: 3

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

Try this:

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

Edit: You've made your question a little more clear. This should do the trick:

setInterval(function(){ location.reload(); }, 5000);

Upvotes: 1

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Try using window.location.reload(); like below for an auto refresh script,

<script>
    setTimeout(function () {
       window.location.reload();
    }, 5000);
</script>

Upvotes: 0

Related Questions