2

I am seeking some help. I am very new to programming and I’m working on a new project.

The objective is to display the contents of a plain text file in a web page.

The text file (named title.txt) and has a single line of text The text file is located on my server The text content changes every three minutes or so.

I wish to read this file and display its content in a web page The web browser is to automatically re-read the file every three minutes or so.

I have looked at a number of websites to achieve this, however i am confused by the options available. I read that Jquery/ajax can perform this task.

Can anyone help me by providing some example code.

Many thanks Colin

Colin Davis
  • 61
  • 1
  • 2
  • 6
  • Make an *Ajax* request within a timer, E.g. [Auto Load and Refresh Div every 10 Seconds with jQuery](http://stackoverflow.com/questions/3121285/auto-load-and-refresh-div-every-10-seconds-with-jquery) - there are many answers if you google for *jquery ajax load every n seconds* – Alex K. Nov 26 '15 at 16:04
  • You can read the file whit a server side application based on a proper language like eg: php – ScaisEdge Nov 26 '15 at 16:10

2 Answers2

3
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>

<Body>

<p><center>Current Track: <span id="trackinfo">No track information available at this time</span></p></center>

<script>
function radioTitle() {

var url = 'http://XXX.no-ip.org:8000/tracktitle.txt'; 

$.ajax({
   type: 'GET',
   url: url,
   dataType: 'text',
   success: function(data) {

   $("#trackinfo").html(data)
},

error: function(e) {
   console.log(e.message);
}

});

}

$(document).ready(function(){

setTimeout(function(){radioTitle();}, 2000);
setInterval(function(){radioTitle();}, 15000);

});

</script>

</body>
</head>
</html>
Colin Davis
  • 61
  • 1
  • 2
  • 6
2
var tid = setInterval(mycode, 2000);
function mycode() {
  // do some stuff...
  // no need to recall the function (it's an interval, it'll loop forever)
readTextFile("your file path");

}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}
Nisha Salim
  • 687
  • 5
  • 13