Click to See Complete Forum and Search --> : Reading data from a text file.
Windchill
05-23-2003, 11:05 AM
(another newb question)
Is there any way to read data from a text file in to a variable? The file would be in the same folder as the javascript.
khalidali63
05-23-2003, 11:19 AM
JavaScript itself is not equipped with any a tools to read data from files on a local machine,however ,you can use Java applets, or ActiveXControl to get this done,
Recomendation will be to use server side programminglang to do this.
Windchill
05-23-2003, 11:22 AM
Server side language? How would you use PHP3 for example?
(Hmm PHP forum or JavaScript forum?)
Charles
05-23-2003, 11:24 AM
#!user/local/bin/perl
use CGI qw(header);
open TEXT, q|someTextFile.txt|;
my @text = <TEXT>;
print header (-type => q|text/javascript|), qq|var text = '@text'|;
Get that up and running on the server and named 'include.pl' or something that you like better and then call it from your HTML with:
<script src="include.pl" type="text/javascript"></script>
And, since they asked for PHP, here that is...
<?PHP
$filename = "file.txt";
$fp = fopen ($filename, "r");
if ($fp) {
$text = fread ($fp, filesize ($filename));
fclose ($fp);
echo $text; // prints text to the screen
}
else {
echo ("File is not readable");
}
?>
Windchill
05-23-2003, 11:31 AM
Yes thank you... But how do I load it into a variable or variables?
Are you talking a javascript varible? Because it is in the PHP variable $text right now...
Windchill
05-23-2003, 11:36 AM
Sorry... Yes I am talking about a javascript variable.
Like this:
<?PHP
$filename = "file.txt";
$fp = fopen ($filename, "r");
if ($fp) {
$text = fread ($fp, filesize ($filename));
fclose ($fp);
}
?>
<html>
<head>
<title>Load PHP file into Javscirpt variable</title>
<script language="javascript" type="text/javascript">
var textfromfile = "<?PHP echo $text; ?>";
</script>
</head>
<body>
</body>
</html>
Windchill
05-23-2003, 11:45 AM
Wow... I never new that PHP and Javascript could work so closely.
One last (dumb) question: Will this work on my computer or does PHP need to be uploaded to a host first?
PHP only runs on a server, so unless you have a server installed on your computer, you will have to upload it to a server that supports PHP first. I personally have a testing server installed on my computer, so PHP works for me.
Windchill
05-23-2003, 11:55 AM
OK thanks. (wanders off to read his Apache guide)
I love the fact that Mac OS X comes with Apache pre installed. I wonder if it supports PHP or wether I have to install it :o
No, you will have to install seprately. http://www.php.net/downloads.php
Windchill
05-23-2003, 12:11 PM
Thanks again