0

I have my php file which contains my method to update the database. However, in Javascript how do I make it so every 5 seconds say it "visits" this page so it's contents gets updated.

Here is my update.php file:

<?php include('config.php') ?>

<?php
mysql_query("UPDATE paint SET paint_points='test'") or die(mysql_error());
echo "Updated";
?>

Sorry, I'm not familiar with the terminology.

Thanks

4
  • You need to use AJAX. Commented Mar 6, 2013 at 18:43
  • use javascript setInterval and AJAX to send request to php for updating Commented Mar 6, 2013 at 18:45
  • Check for a javascript framework such as jQuery ($.ajax) there is all the code you need to do it. Commented Mar 6, 2013 at 18:45
  • Specially, you'll have a separate page that hosts the JavaScript call. You'll make an asynchronous call to update.php on a recursive loop. (or recursive promise/deferred) Commented Mar 6, 2013 at 18:46

3 Answers 3

2

Use the setInterval function with an (a)jax request every 5 secs in javascript:

//syncronized jax:
function myjax() {
    var oXhr = new XMLHttpRequest();
    oXhr.open("POST", "yourphp.php", false);
    oXhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
    oXhr.send(null);
}

//set an interval each 5 seconds to call your myjax method
setInterval(function() { myjax(); }, 5000);

In this example the request is synchronous but it could be asynchronous if you wished so.

Sign up to request clarification or add additional context in comments.

Comments

1

The simplest case is to reload the page with:

<script type="text/javascript">
 setInterval(function() { location.reload(true); }, 5000);
</script>

You can get fancier if you use an ajax call to fetch the page.

2 Comments

I don't think the OP is looking to reload the entire page.
@SudiptaChatterjee Maybe, however, it's not clear. One could wrap it into an iframe, if they don't feel comfortable with ajax.
0

Using jQuery:

(function() {
    var updateAgain = arguments.callee;
    $.get('/url/to/script.php', function() {
        setTimeout(updateAgain, 5000);
    });
})();

The advantage of this over setInterval is that it won't start counting to five seconds until the request is finished; this is important if the request takes more than a second or two. It will also stop if a request fails (which may or may not be an advantage).

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.