name_masked
name_masked

Reputation: 9793

Refresh PHP Page using ajax

I have a php page that needs to be refreshed every 5 secs. On embedding the ajax file, I don't find the updates taking place in Firebug. Here is the skeleton of the code:

**notification.php**
<?php
       ....
       ....
?>
<html>
     <head>
     <script src="./refresh.js"></script>
     <script type="text/javascript">
         refreshContents();
     </script>
     </head>
     <body>
            ....

            <div id="identifier">
               <p>Waiting area</p>
            </div>
      </body>
</html>


**refresh.js**

var seconds = 5;
var content = "identifier";
var url = "notification.php";

function refreshContents()
{
   var xmlHttp;
   try
   {
      xmlHttp = new XMLHttpRequest();
   }
   catch(e)
   {
      try
      {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch(f)
      {
         try
         {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch(g)
         {
            alert("Browser not supports Ajax");
            return false;
         }
      }
   }


   xmlHttp.onreadystatechange=function()
   {
      if (xmlHttp.readyState == 4)
      {
         document.getElementById(content).innerHTML = xmlHttp.responseText;
         setTimeout('refreshContents()', seconds*1000);
      }
   }

   xmlHttp.open("GET", url, true);
   xmlHttp.send(null);
}

var seconds = 5;
window.onload = function startrefresh(){
   setTimeout('refreshContents()', seconds*1000);
}

Upvotes: 0

Views: 20857

Answers (3)

Gaurav Gupta
Gaurav Gupta

Reputation: 518

see the following example :

<html>
<head>
<title>Refresh a page in jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<button id="PageRefresh">Refresh a Page in jQuery</button>
<script type="text/javascript">
$('#PageRefresh').click(function() {
          location.reload();
});
</script>
</body>
</html>

this code definetly help you. or we can use -

 <meta http-equiv="refresh" content="5">

Upvotes: 1

Ryan
Ryan

Reputation: 905

Why not just put a <meta http-equiv="refresh" content="5"> tag into your <head>? It will refresh the page every 5 seconds without the need for any javascript.

Upvotes: 3

jrbalsano
jrbalsano

Reputation: 844

Though it may not be the ideal solution, jQuery has a pretty simple way of implementing exactly this:

$(document).ready(function () {
  function reload() {
    $("#content").load("notification.php");
  }
  setTimeOut(reload, seconds*1000)
}

I'm not sure that will work perfectly, haven't done it in a little while, but its a much more elegant solution I do believe.

Upvotes: 9

Related Questions