Question

I would like to know how to execute a PHP code periodically (for example every 5 seconds) using AJAX. This is the PHP code that I want to execute periodically:

<?php
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)){
  echo "a new event was added";
}
?>

In fact, I am started in AJAX so is there anyone who can provide me a simple example about how to do that?

Was it helpful?

Solution

Do you know what exactly is AJAX?

It looks like you will be using a library for this, so take a read here: http://api.jquery.com/jquery.ajax/

If you are not planning to use jQuery, you could check this XMLHttpRequest project that is cross-browser: https://github.com/ilinsky/xmlhttprequest

Make use of AJAX periodically using a setInterval of 5 seconds where you would make a call to a PHP file you have in your server that would run the code you specified.

Take the following example:

index.html

setInterval(function() {
    $.get("file.php", function (data) {
       console.log('Good to go, data was loaded');
       console.log(data);
    });      
}, 5000);

file.php

<?php
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)){
  echo "a new event was added";
}
?>

OTHER TIPS

You can use an interval and jQuery get() function:

var myInterval = setInterval(function() {
   $.get( "(YOUR URL)", function( data ) {
      alert( "Load was performed." );
   });      
}, 5000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top