Jump to content
xisto Community
pasten

Php - Fetching Random Line From A Text File and displaying it using AJAX/iframe

Recommended Posts

What you should know: HTML, PHP basics (executing php scripts)

Examples:

Using AJAX

Using iframe

Download Examples

 

Using this script you can display a random quote/fact every time a visitor clicks the link. It happens dynamically without reloading the whole page. Useful for keeping a site fresh and lively. For example, you can have it in "About Me" page of a website which is rarely updated. All the quotes are stored in a text file separated by a line break. Although I have included a sample collection, you are free to modify or create your own. Thanks to David Pye for offering such a huge collection of facts. His site too contains a random line fetcher, but what I am going to tell is a bit different and will also contain a link to view another random quote without refreshing.

 

If you are interested in this script, I recommend you go through this tutorial instead of just downloading the script. Because, the files in the download was actually made for one of my friends static php website and hence contains a lot of bulky code and styling which might confuse you.

 

Using AJAX:

 

Ok, so first we will use AJAX and the php script which displays the output. Let's save the script as did-you-know.php:

 

 

<?phpsrand ((double)microtime()*1000000);$f_contents = file ("did-you-know.txt");$line = $f_contents[array_rand ($f_contents)];print $line;?>
You can download "did_you_know.txt" and save it to the same directory as your php script. Bascially, the whole text file is saved into an array and then a random row is extracted using php's built in function array_rand(). array_rand() can also extract several lines by supplying an extra argument that specifies how many random elements you want and it returns the keys for them in an array.

 

Now for the main display file which shows the quotes. Save it as anything like random-quote.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd;

<html xmlns="https://w3.org/1999/xhtml/;

<head>
<title>Random line fetcher - Using Ajax</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script type="text/javascript">
//Create a boolean variable to check for a valid Internet Explorer instance.
var xmlhttp = false;

//Check if we are using IE.
try {

//If the Javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {

//If not, then use the older activex object.
try {

//If we are using Internet Explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {

//Else we must be using a non-IE browser.
xmlhttp = false;
}
}

//If we are using a non-IE browser, create a javascript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
function makerequest(serverPage, objID) {
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
</script>
</head>

<body onload="makerequest('did-you-know.php','fact')">
<div>
ďż˝<div id="fact"></div>
ďż˝<a href="did-you-know.php" onclick="makerequest('did-you-know.php','fact'); return false;">Yes! Next one please...</a>
</div>
</body>
</html>

 

 

The basic javascript defines an instance of the object depending on whether the browser is IE or not.

<body onload="makerequest('did-you-know.php','fact')">

The body onload displays random quote when the page is first viewed or when it is refreshed.

<a href="did-you-know.php" onclick="makerequest('did-you-know.php','fact'); return false;">Yes! Next one please...</a>

onclick invokes the function makerequest which calls the php script and puts the quote in the div with id "fact".

 

That\'s all. Now upload all the three files and view "ranom-quote.php".

 

I was unable to execute it correctly in IE. Any help, please? Here is the complete short code as given above: barebones_using_ajax.zip.

 

Using iframe:

In the mean time, I have created the script using iframe. Its very simple, any way here is the modified visual for it (random-quote.php). The php script (did-you-know.php) is the same as given above. Here we don't require javascript at all.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd;<html xmlns="https://w3.org/1999/xhtml/;

<head>
<title>Random line fetcher - Using iframe</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>

<body>
<div>Did You Know?</div>
<div>
ďż˝<iframe src="did-you-know.php" id="fact" title="fact"></iframe>
ďż˝<a href="did-you-know.php" target="fact">Yes! Next one please...</a> ďż˝
</div>
</body>
</html>

Update: External download links not working. Download the attachments.

did_you_know.zip

Edited by OpaQue (see edit history)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.