13

Am trying to refresh data stored in a div every 10 seconds using jQuery.

My HTML code is:

<!DOCTYPE html>
<head>
<title>Untitled Document</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
    $(document).ready(function(){
        setInterval(function() {
            $("#latestData").load("getLatestData.php #latestData");
        }, 10000);
    });

</script>
</head>

<body>
    <div id = "latestData">

    </div>
</body>
</html>

And the PHP code I am using (temporarily as I know this won't change due to the same "data"):

<?php

    echo "test";

?>

However, it isn't even showing "test" on the html page.. could anyone suggest where I have gone wrong?

Many thanks

New_programmer
  • 285
  • 3
  • 7
  • 16

3 Answers3

10

jQuery load method works in a different way. Try reading its documentation.

You don't have to specify destination element ID twice, remove the second one, like this:

$("#latestData").load("getLatestData.php");
ulentini
  • 2,413
  • 1
  • 14
  • 26
  • Ah yes perfect, knew it would be something simple! Many thanks! One other small question, the text only appears after 10 seconds have passed, is there a way for it to appear straight away and then refresh after 10 seconds too? – New_programmer Apr 14 '13 at 12:12
  • 1
    @New_programmer There are a lot of ways to do this, look at this question: http://stackoverflow.com/questions/6685396/execute-the-first-time-the-setinterval-without-delay – ulentini Apr 14 '13 at 12:15
5

Here's a way that will solve what you want to achieve, using the $.get method in jQuery:

$(document).ready(function () {
    setInterval(function() {
        $.get("getLatestData.php", function (result) {
            $('#latestData').html(result);
        });
    }, 10000);
});
Jason Lipo
  • 751
  • 2
  • 11
  • 24
0

If you want to refresh message count just use this code:

$(document).ready(function () {
    setInterval(function () {
        $("#ID").load();
    }, 1000);
});
MarcoS
  • 17,323
  • 24
  • 96
  • 174
vishal
  • 1