Page 1 of 1

PHP->Javascript wierdness

Posted: Wed Jun 28, 2006 7:17 pm
by dmrdev
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi all,

I've got some pretty wierd behavior going on here and I was hoping someone might be able to shed some light on it...

I'm reading a simple .txt file into a string w/ php so I can pass it to javascript to use. So here's what I've got.

Code: Select all

//open the correct text file
$fh = fopen($path, "r") or die("Can't open file");
$contents = fread($fh,filesize($path));
fclose($fh);

//define array of strings
$captions = explode("|",$contents);
//print the caption array to test it
echo "<br />";
for ($i=0; $i<count($captions); $i++){
		echo $captions[$i];
		echo $i;
		echo "<br />";
		}
$strContent = implode("|",$captions);
echo $strContent;
echo "<br>";
//no problem so far

Then in the body I have

Code: Select all

<script type="text/javascript">
<!--
document.write("This begins the Javascript");
var strContent = "<?php echo $strContent; ?>"; // this line seems to make it or break it
document.write(strContent);
// -->
</script>
When I run this no Javascript code at all is displayed.
If I comment out the JS line where I define var strContent, still nothing is displayed.
If I completely take out the JS line where I define var strContent then the Javascript message is displayed.
Finally, if I define $strContent in the PHP section with a static string, say $strContent = "static string", instead of the implode function, the Javascript works fine.

What gives? Any thoughts here?
I even tried kicking my monitor but still no luck...


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Wed Jun 28, 2006 7:24 pm
by feyd
You may need to pass the data through addslashes() so that carriage returns among other special characters are escaped.

Posted: Wed Jun 28, 2006 7:27 pm
by Robert Plank
Show the contents of the txt file... I think you have line breaks in the text file and trying to put it in a JavaScript variable. Can't do that.

Posted: Sun Jul 02, 2006 8:29 pm
by dmrdev
My apologies for the code format faux pa. I'll make a note of that for next time...

It WAS those pesky line breaks - Thanks for the input!