user3838972
user3838972

Reputation: 331

AJAX jQuery refresh div every 5 seconds

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?

Upvotes: 29

Views: 217577

Answers (5)

Dudar Mykola
Dudar Mykola

Reputation: 87

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);
        }
    });
}

Upvotes: 5

Elamparuthi
Elamparuthi

Reputation: 31

<script type="text/javascript">
$(document).ready(function(){
  refreshTable();
});

function refreshTable(){
    $('#tableHolder').load('getTable.php', function(){
       setTimeout(refreshTable, 5000);
    });
}
</script>

Upvotes: 3

Yunus Aslam
Yunus Aslam

Reputation: 2466

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.

Upvotes: 59

Maneesh Singh
Maneesh Singh

Reputation: 575

you can use this one.

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

you java script code should be like that.

setInterval(function(){
      $('#test').load('test.php');
 },5000);

Upvotes: 3

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17566

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>

Upvotes: 7

Related Questions