29

I got this code from a website which I have modified to my needs:

<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
</head>

<div id="links">

</div>

<script language="javascript" type="text/javascript">
var timeout = setTimeout(reloadChat, 5000);

function reloadChat () {
$('#links').load('test.php #links',function () {
        $(this).unwrap();
        timeout = setTimeout(reloadChat, 5000);
});
}
</script>

In test.php:

<?php echo 'test'; ?>

So I want test.php to be called every 5 seconds in links div. How can I do this right?

user3838972
  • 331
  • 1
  • 5
  • 10

5 Answers5

59

Try this out.

function loadlink(){
    $('#links').load('test.php',function () {
         $(this).unwrap();
    });
}

loadlink(); // This will run on page load
setInterval(function(){
    loadlink() // this will run after every 5 seconds
}, 5000);

Hope this helps.

Yunus Aslam
  • 2,447
  • 4
  • 25
  • 39
7

Try using setInterval and include jquery library and just try removing unwrap()

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">

var timeout = setInterval(reloadChat, 5000);    
function reloadChat () {

     $('#links').load('test.php');
}
</script>

UPDATE

you are using a jquery old version so include the latest jquery version

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
  • this script works but the first seconds there is no content in the div. can the content also load on page load ? – Bombelman Feb 15 '23 at 03:07
5

Try to not use setInterval.
You can resend request to server after successful response with timeout.
jQuery:

sendRequest(); //call function

function sendRequest(){
    $.ajax({
        url: "test.php",
        success: 
        function(result){
            $('#links').text(result); //insert text of test.php into your div
            setTimeout(function(){
                sendRequest(); //this will send request again and again;
            }, 5000);
        }
    });
}
Marco Di Francesco
  • 35
  • 1
  • 4
  • 14
Dudar Mykola
  • 89
  • 1
  • 2
3

you can use this one.

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

you java script code should be like that.

setInterval(function(){
      $('#test').load('test.php');
 },5000);
Maneesh Singh
  • 555
  • 2
  • 12
3
<script type="text/javascript">
$(document).ready(function(){
  refreshTable();
});

function refreshTable(){
    $('#tableHolder').load('getTable.php', function(){
       setTimeout(refreshTable, 5000);
    });
}
</script>
Mayank Patel
  • 3,868
  • 10
  • 36
  • 59