Jump to content

run a function every second without reloading page.


MadnessRed

Recommended Posts

ok, could someone help me as I am a bit stuck.

What i want is for a php script to run every x seconds, then if the script returns true I want it to reload the page.

 

so here is an example.

 

//loop this code ever 1 second
loop{
    $qry = mysql_query("select * from `table` where `read` = '0' ;");
    if(mysql_num_rows($qry) > 0){ header("location: messages.php"); }
}

 

the actually code is not real but it shows what I would like, also the loop is made up. but I am wondering if there is a real version or something similar.

 

 

You'll need to look into AJAX. Your client side script (JS) will count the x seconds, and then send behind the scenes a request to your server. The server will check if there are new records, and return the result (true/false) back to the client side script. From there the script could decide whether to reload the page or not.

 

The whole "behind the scenes" part is done using AJAX.

 

Orio.

Make sure to respect your hosts resources (if you have a web host). Making a request to the server every so often can put a large load on the web server.

 

Here is your sample AJAX/JavaScript:

 

function ajaxPost(){
   var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
   var ajaxRequest;
   try{
      ajaxRequest = new XMLHttpRequest();
   } catch (e){
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e){
            alert("Your Browser Doesn't support AJAX.");
            return false;
         }
      }
   }
   return Array(ajaxRequest,contentType);
} 

setInterval ( "myFunction()", 30000 ); // every seconds
function myFunction(){
   connect = ajaxPost();
   connect[0].onreadystatechange = function(){ 
      if(connect[0].readyState == 4){
         eval(connect[0].responseText);
         alert(cTime);
      }
   }
   var va = '';
   connect[0].open("POST", '/mypage/file.php', true);
   connect[0].setRequestHeader("Content-Type", connect[1]);
   connect[0].send(va);
}

 

 

Your example PHP:

 

if(date("a") == 'am'){
     echo 'var cTime = "Good Morning!";';
}else{
     echo 'var cTime = "Good Evening!";';
}

ahh, thats sounds complicated.

 

is it possible to reload one frame from another

 

so I have 1 page which reloads every second and a second which page whch can be reloaded from the first page.

 

<script type="text/javascript">
parent.frameName.location.reload(true);
</script>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.