0

I have had a look thorugh similar questions, but haven't quite found what I am looking for...

I have a webpage written in PHP and I need to display the content of an external .txt file and I need that to refresh every, say, 20 seconds as the .txt files contents change on a regular basis.

I have been able to achieve this by putting in an IFRAME and using PHP include to display the content of the file. I then refresh the include page every 20 seconds.

This works fine EXCEPT, the IFRAME refreshes are causing havoc with my websites stats because of the amount of refreshes, ehcih count against pageviews.

Can I use, say, AJAX or something else to do this? I'm sure they may be another way of doind this without seriously affecting my stats and without causing as much of a load on the server?

Please kindly provide as much specific intructions as possible, as it's already taken me days to acheive what I already have!

Many thanks in advance!

Ozzy
  • 7,817
  • 7
  • 50
  • 92
omega1
  • 785
  • 3
  • 14
  • 31
  • Can't you just put the external .txt file straight in the iframe, so that client load it directly from the source server? If not, you will have to adjust they way that you collect your stats so that the AJAX requests don't `count against pageviews` – DaveRandom Apr 16 '12 at 11:06
  • Are you refreshing the page or iframe? It is easy to re-load iframe's content if it is on the same domain. – Salman A Apr 16 '12 at 11:32

5 Answers5

1

I know you asked for Ajax/JavaScript but Java Applets work with most desktop browsers and this task would be quite simple in Java, so I've made you an example of how you would do that with a Java applet.

// PHP/HTML embed code
<APPLET CODE="readTextFile.class" width=400 height=300>
    <PARAM NAME="fileToRead" VALUE="<?php echo $textfile ?>">
    Your browser does not support the <code>applet</code> tag.
</APPLET>

You will need to compile the java file like javac "path/to/readTextFile.java" in cmd.exe

// readTextFile.java

import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class readTextFile extends Applet {

   String fileToRead = "path/to/myfile.txt";
   StringBuffer strBuff;
   TextArea txtArea;

   public void init(){
       txtArea = new TextArea(300, 400);
       txtArea.setEditable(false);
       add(txtArea, "center");

       // First try the HTML applet parameter, if not use fileToRead variable
       String prHtml = this.getParameter("fileToRead");
       if (prHtml != null) fileToRead = new String(prHtml);

       // Set up a timer to read the file every 20 seconds
       Timer t = new Timer();
       t.scheduleAtFixedRate(new TimerTask() {
           public void run() {
               readFile();
           }
       }, 0, 20*1000);
   }

  public void readFile(){
       String line;
       URL url = null;
       try{
           url = new URL(getCodeBase(), fileToRead);
       } catch (MalformedURLException e) {
           //handle or do nothing
       }

       try {
           InputStream in = url.openStream();
           BufferedReader bf = new BufferedReader(new InputStreamReader(in));
           strBuff = new StringBuffer();
           while((line = bf.readLine()) != null){
               strBuff.append(line + "\n");
           }
           txtArea.append("File Name : " + fileToRead + "\n");
           txtArea.append(strBuff.toString());
       } catch(IOException e) {
           e.printStackTrace();
       }
   }
}

That will read the file every 20 seconds from your server. Just make sure the file you try to access is in the same folder or below (but not above) wherever you place readTextFile.class

Note that the text file will get just as many crazy hits (but theres no way around that) but your page wont get crazy hits.

Ozzy
  • 7,817
  • 7
  • 50
  • 92
1

if you're using jquery you can try this code: it wil fetch the text file and place the content inside the div with the id textdiv

<script type='text/javascript'>
var doInterval;
function getfile() {
  $.ajax({
    url: "file.txt",
    complete: function(request){
      $("#textdiv").html(request.responseText);
    }
  });
}
doInterval = setInterval(getfile, 20000);
</script>
<div id="textdiv"></div>
AL-Kateb
  • 2,816
  • 3
  • 16
  • 20
0

You can definitly use something like Comet/Long Polling with PHP, but as the accepted answer to this question mentions, there are some caveats when using e.g. Apache as a server.

If you're not limited to PHP, you could use socket.io, which is ideally suited for the cause. Also, if you don't have too many clients, Comet could still be ok for you.

Community
  • 1
  • 1
mistalee
  • 871
  • 6
  • 14
0

I would hide the Google Analytics JavaScript based on a session, so that it only loads once for that session:

<?php
session_start();
if (!isset($_SESSION['beenHere']) || !$_SESSION['beenHere']) {
?>
  <!-- ga.js javascript here -->
<?php
} else {
  $_SESSION['beenHere'] = true;
}
?>

Then you can continue reloading the page as you wish. This is presuming, however, that you need to load the text file with PHP? Otherwise, can you not just load the text file in to the iFrame, and use a JavaScript setTimeout call to refresh the iframe src?

LeonardChallis
  • 7,728
  • 5
  • 42
  • 72
0

I would suggest Prototype ; It supports periodical update, out of the box! Get and include that prototype JS script on your page (download it from here). Then add this script in script block.

new Ajax.PeriodicalUpdater('logger', 'path/to_file.php',
{ 
    method:'post',
    parameters: {sender:'mrigesh',reciever:'browser'},
    frequency: 20,
    decay: 2
});

So your 'path/to_file.php' will be providing the portion of info that needs to be updated regularly. See alter frequency to as per your like (I saw 20 in your question!). Decay is a feature that lets delaying the period of request sent to server if same data is received again and again... API Path: read