105

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
user760220
  • 1,207
  • 2
  • 13
  • 12

6 Answers6

131

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:

http://api.jquery.com/load/

e.g.

$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
user1721135
  • 6,864
  • 8
  • 34
  • 63
  • 6
    Hey man, just found out that you are a missing a space after the ' (colon right?), this example did not work out of the box :-) $('#thisdiv').load(document.URL + ' #thisdiv'); – David Reinberger Jan 07 '14 at 21:20
  • 17
    This method has a big disadvantage. If you use this and the part of the page reloads you can't do the same JQuery/Ajax action again without reloading whole page in browser. After the reload with this method JQuery is not initalized / will not work again. – Marcel Wasilewski Nov 13 '15 at 13:46
  • 2
    are you sure we need a space before # tag? I worked for me if I remove #tag. – Kurkula May 08 '16 at 08:26
  • this solution hase a probleme, it create a duplicate div inside the parent div – Touhami Feb 16 '17 at 15:47
  • 1
    @Touhami no it doesn't, that's the point. See: http://jsbin.com/sikiyazeji/edit?html,css,js,output – user1721135 Feb 17 '17 at 16:57
  • @Touhami I'm having the same issue, did you ever resolve it? – Greg Hilston Mar 10 '17 at 20:19
  • 1
    @GregHilston I creat a div inside other div so I load the parent Div and put it in the child Div – Touhami Mar 13 '17 at 12:45
  • 2
    @GregHilston here is my js code $('#dashboard_main_content').load(document.URL + ' #dashboard_content'); and here is my HTML
    Content
    – Touhami Mar 13 '17 at 18:43
  • For current chrome version it should be: `$('#thisdiv').load(document.URL + ' #thisdiv *');` – pguardiario Nov 06 '17 at 07:08
  • 1
    Worked. Thank you – Tariq Ahmed Nov 28 '17 at 22:35
  • 3
    `$('#thisdiv').load(document.URL + ' #thisdiv>*')` prevents having another `#thisdiv` inside the original `#thisdiv` – Peter Dec 16 '17 at 21:17
  • 1
    The issue you have described, @MarcelWasilewski, is the one I am currently facing. The div will reload once and once only. Is there a way to bypass this? – Axelle Jul 17 '19 at 14:36
  • @Axelle Have you already found a solution? There are several ways to do this. It depends on the environment. The cleanest way, in my eyes, always is to just send Json to the backend and the other way around so you dont even have to entirely reload parts of the page but just replace the data. I can offer you to have a look at it, but might be too long for a comment in here. – Marcel Wasilewski Jul 22 '19 at 15:12
  • 1
    @MarcelWasilewski I've found the solution. It turns out in my case I was using setTimeout instead of setInterval - which means my code was actually running correctly. Thank you though :) – Axelle Jul 23 '19 at 14:10
19

Let's assume that you have 2 divs inside of your html file.

<div id="div1">some text</div>
<div id="div2">some other text</div>

The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.

You can, however, communicate between the server (the back-end) and the client.

What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.

Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.

setInterval(function()
{
    alert("hi");
}, 30000);

You could also do it like this:

setTimeout(foo, 30000);

Whereea foo is a function.

Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.

A classic AJAX looks like this:

var fetch = true;
var url = 'someurl.java';
$.ajax(
{
    // Post the variable fetch to url.
    type : 'post',
    url : url,
    dataType : 'json', // expected returned data format.
    data : 
    {
        'fetch' : fetch // You might want to indicate what you're requesting.
    },
    success : function(data)
    {
        // This happens AFTER the backend has returned an JSON array (or other object type)
        var res1, res2;

        for(var i = 0; i < data.length; i++)
        {
            // Parse through the JSON array which was returned.
            // A proper error handling should be added here (check if
            // everything went successful or not)

            res1 = data[i].res1;
            res2 = data[i].res2;

            // Do something with the returned data
            $('#div1').html(res1);
        }
    },
    complete : function(data)
    {
        // do something, not critical.
    }
});

Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.

I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.

Jonast92
  • 4,964
  • 1
  • 18
  • 32
11

You need to do that on the client side for instance with jQuery.

Let's say you want to retrieve HTML into div with ID mydiv:

<h1>My page</h1>
<div id="mydiv">
    <h2>This div is updated</h2>
</div>

You can update this part of the page with jQuery as follows:

$.get('/api/mydiv', function(data) {
  $('#mydiv').html(data);
});

In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.

See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/

jsalonen
  • 29,593
  • 15
  • 91
  • 109
7

Usefetch and innerHTML to load div content

let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
  setTimeout(refresh,2000);
}
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s
  </button>
</div>

<div id="dynamicPart">Dynamic part</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request. among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .

Community
  • 1
  • 1
Mr. Mak
  • 837
  • 1
  • 11
  • 25
1

I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:

Include jQuery in your code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Create the following function:

<script type="text/javascript">
    function loadcontent() {
      $("#test").load("test.html");
      //add more lines / divs 
    }
</script>

Load the function after the page has loaded; and refresh:

<script type="text/javascript">
    $( document ).ready(function() {
      loadcontent();
    });
    setInterval("loadcontent();",120000);
</script>

The interval is in ms, 120000 = 2 minutes. Use the ID you set in the function in your divs, these must be unique:

<div id="test"></div><br>