Search code examples
javascriptphphtmlrandomflat-file

Fetching Random Line From Flat Text File Database


I am interested whether the following php script can be written in Javascript (or HTML5)? Basically that is just a simple file reading a .txt and displaying a random line from it:

<?php
$text = file_get_contents('flatFileDB.txt');
$textArray = explode("\n", $text);
$randArrayIndexNum = array_rand($textArray);
$randPhrase = $textArray[$randArrayIndexNum];
?>
<html>
<body>
<h2><?php echo $randPhrase; ?></h2>
</body>
</html>

Example of 'flatFileDB.txt':

Line 1
Line 2
Line 3
Line 4
Line 5
...
...
etc

The example is taken from here: http://www.developphp.com/view.php?tid=1213, and I would like to do the same, but without server-side php. Is it even possible?


Solution

  • Assuming that the flat file DB can be accessed at http://www.example.com/flatFileDB.txt and your HTML file has a div with an id value of random-phrase:

    var request = new XMLHttpRequest();
    request.onload = function() {
        // get the file contents
        var fileContent = this.responseText;
        // split into lines
        var fileContentLines = fileContent.split( '\n' );
        // get a random index (line number)
        var randomLineIndex = Math.floor( Math.random() * fileContentLines.length );
        // extract the value
        var randomLine = fileContentLines[ randomLineIndex ];
    
        // add the random line in a div
        document.getElementById( 'random-phrase' ).innerHTML = randomLine;
    };
    request.open( 'GET', 'http://www.example.com/flatFileDB.txt', true );
    request.send();
    

    Look here for the documentation on XMLHttpRequest which allows you to retrieve files asynchronously.