1

I'm displaying the cotntent of a text file on web page(say between <div id='text'></text>) this file's content is edited by any user who view the page, I already use ajax to write to the file and display to the current user, but if there are any users browsing the page at the same moment they have to refreh the page to see the new edited content. I want to know how to use ajax to make the part that contain the file content remain updated continmuosly without refreshing the page

<script type='text/javascript'>
function change(){

    if (window.XMLHttpRequest)  xhr=new XMLHttpRequest();
    else      xhr=new ActiveXObject("Microsoft.XMLHTTP"); //IE5

    xhr.onreadystatechange=function()
      {
        if (xhr.readyState==4 && xhr.status==200)
        {
            if(xhr.responseText=="empty") return;
            document.getElementById("space").innerHTML=xhr.responseText;
        }
     }
    var str=document.getElementById('msg').value;
    document.getElementById("msg").value="";    
    xhr.open("GET","response.php?q="+str,true);
    xhr.send();           
}
</script>

<center>
<div id='space'>nothing</div>
<input type='text' name='msg' id='msg'>
<input type='button' onClick='change()' value='Click'>
</center>
deceze
  • 510,633
  • 85
  • 743
  • 889
Ahmed Waheed
  • 1,281
  • 5
  • 21
  • 39

2 Answers2

0

The simplest way to accomplish the "server push" effect is through polling.

In your case, you can add this functionality by adding a simple Javascript statement:

window.onload = function()
{
    setInterval("change();", 5000);
};

This code will call change(); every 5000 ms.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
  • actually I want the view updated just when the file content is updated by other user, i.e when a user hit some button....how can I do this?, because this looks a bit like keeping refreshing the page. – Ahmed Waheed Jul 12 '11 at 06:47
  • Without WebSockets widely implemented, this is one method there is as a fallback. Try opening Gmail with Firebug... you won't like what you see. If you're interested in some other (equally hacky) methods, look up "Comet" or "iframe reverse AJAX". – Zach Rattner Jul 12 '11 at 15:14
0

You could use setInterval() to perform a periodic AJAX query to check for updates. Then, if needed,update the content on the page.

Diff.Thinkr
  • 855
  • 1
  • 8
  • 16
  • I tried it, but it looks a bit like refresh, my script is actually a simple chat script, when I tried setInterval() it behaves like refresh so that the sender can't complete writing in the text box at the moment the interval pass. – Ahmed Waheed Jul 12 '11 at 06:51
  • I've also seen some stuff about using a background page that passes the data around and maintains the continuous communications. I've never tried this myself but it seemed promising. – Diff.Thinkr Jul 15 '11 at 12:30