Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 554
user3838972 Avatar asked Aug 22 '14 12:08

user3838972


3 Answers

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.

like image 66
Yunus Aslam Avatar answered Oct 22 '22 06:10

Yunus Aslam


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>
like image 7
Kanishka Panamaldeniya Avatar answered Oct 22 '22 04:10

Kanishka Panamaldeniya


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);
        }
    });
}
like image 5
Dudar Mykola Avatar answered Oct 22 '22 06:10

Dudar Mykola