jaesson1985
jaesson1985

Reputation: 748

How do I refresh a DIV content?

<div id='here'></div>

I am trying to refresh a certain div within a bunch of divs. The div content is basically generated by PHP along with data from a MySQL database in addition to many variables being sent with the help of an XMLHttpRequest.

The idea is to reload/refresh the div itself and not load a php file or to overwrite it with .text or .html. In this case, I cannot use .load('file.php')

What I have tried :

<script type='text/javascript'>
    function updateDiv()
    { 
        document.getElementById("here").innerHTML = document.getElementById("here").innerHTML ;
    } 
</script>

and (for a every 3 second refresh) :

$(document).ready(function () {
    setInterval(function () {
        $('#here').load('#here'));
    }, 3000);
});

Ideally, I would require something like :

function reloadDIV () {document.getElementById("here").innerHTML.reload}

function reloadDIV () {$('#here').load(self)} 

so that I can use it in a onClick :

<a onclick='reloadDIV ();'>reload div</a>

Upvotes: 44

Views: 382840

Answers (5)

Gass
Gass

Reputation: 9344

You can do the following to just reload a <div> element:

$('#yourDiv').load('#yourDiv > *')

Make sure to: use an id and not a class. Also, remember to paste: <script src="https://code.jquery.com/jquery-3.5.1.js"></script> in the <head> section of the HTML file, if you haven't already. In opposite case it won't work.

Upvotes: 3

Steve
Steve

Reputation: 20469

To reload a section of the page, you could use jquerys load with the current url and specify the fragment you need, which would be the same element that load is called on, in this case #here:

function updateDiv()
{ 
    $( "#here" ).load(window.location.href + " #here" );
}
  • Don't disregard the space within the load element selector: + " #here"

This function can be called within an interval, or attached to a click event

Upvotes: 70

pc_
pc_

Reputation: 578

Complete working code would look like this:

<script> 
$(document).ready(function(){
setInterval(function(){
      $("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>

<div id="here">dynamic content ?</div>

self reloading div container refreshing every 3 sec.

Upvotes: 12

Aleh Shyliuk
Aleh Shyliuk

Reputation: 310

For div refreshing without creating div inside yours with same id, you should use this inside your function

$("#yourDiv").load(" #yourDiv > *");

Upvotes: 26

Avinash Jain
Avinash Jain

Reputation: 7606

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

Upvotes: 1

Related Questions