0

I have a PHP file called data.php and I want to use jQuery to call the file and return its contents to

<div id="datacontainer"></div>

every 60 seconds. I have found lots of examples on here where the event is triggered onclick but I am struggling to find a solution for a timed event.

What is the best practice way to insert the output of a file named path/to/file/data.php into a div using jQuery/Ajax?

2
  • Use what you've seen from the examples + setInterval() Commented Jan 16, 2014 at 4:40
  • Have you tried any codes already? Commented Jan 16, 2014 at 4:41

3 Answers 3

1
/* set interval to call function every 60 seconds */
setInterval(function(){
/* start ajax */
    $.ajax({
    url: "path/to/file/data.php",
    type: "GET"

    }).done(function(html) {
    /* when it's done, take the return and replace whatever is in the DIV with it 
    if you dont want to replace, but append, just use the .append(html) function */
    $( '#datacontainer' ).html( html );

    });
}
/*60 seconds * 1000 miliseconds*/
,60000);
Sign up to request clarification or add additional context in comments.

Comments

1

Check this out: http://api.jquery.com/load/ and https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval

Example:

setInterval(function() {
    $( "#datacontainer" ).load( "data.php" );
}, 60000);

Also consider using successCallback of jQuery load and setTimeout, as usually you want to wait till server will return contents. In my opinion best practice would be:

var ID = null,
    time = 60000,
    func = function() {
    $( "#datacontainer" ).load( "data.php", function() {
        ID = setTimeout(func, time);
    });
};
ID = setTimeout(func, time);

But it depends on use case.

Comments

0
var $contentdiv = jQuery('#datacontainer');
window.setInterval(function () {
  $contentdiv.load("path/to/file/data.php");
}, 60000);

If you had googled "timer events javascript" you would have found this MDN page...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.