2

I want a php program to be executed every 5 seconds using JavaScript. How can I do that?

I tried using:

<script type="text/javascript">
    setInterval(
        function (){
            $.load('update.php');
        },
        5000
    );
</script>

But it doesn't work.

5
  • 2
    you could use a non-blocking server such as nodejs, or implement your php websocket server Commented Dec 28, 2012 at 8:53
  • AJAX request on a 5 second timer. (Not saying it's a good idea) Commented Dec 28, 2012 at 8:55
  • Use setTitmeout() and ajax Commented Dec 28, 2012 at 8:55
  • better set up a crone job Commented Dec 28, 2012 at 8:57
  • you should make sure that jQuery is loaded at this time so start with $(function() { ... your set interval and other code... }); then it should work. Commented Dec 28, 2012 at 22:01

2 Answers 2

17

Using jQuery and setInterval:

setInterval(function() {
    $.get('your/file.php', function(data) {
      //do something with the data
      alert('Load was performed.');
    });
}, 5000);

Or without jQuery:

setInterval(function() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
         if (request.readyState == 4 && request.status == 200) {
            console.log(request.responseText);
         }
      }
    request.open('GET', 'http://www.blahblah.com/yourfile.php', true);
    request.send();

}, 5000);
Sign up to request clarification or add additional context in comments.

2 Comments

I have a feeling there's some "Downvote the competition" on SO going on, users downvoting other answers on posts they answered.
@Dabido: In that case, I didn't say anything :P Good sportsmanship :D
7

Try using setInterval() to perform a XHR call. (jQuery, non jQuery)

setInterval(function() {
    // Ajax call...
}, 5000);

This will execute your code inside the function every 5 secs

3 Comments

He wants to execute PHP with JavaScript. Not JavaScript with JavaScript. However +1 for helping a help vampire
@ColeJohnson: The only way to execute php from JavaScript is to do a AJAX call, to request a php page.
@Cerbrus I am aware AJAX is the solution. I'm just pointing out that your code doesn't give any indication of Ajax

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.