jrg23y Posted March 9, 2010 Share Posted March 9, 2010 I have been loading a page using: include("myPage.html"); this works great but I would like to set a javascript variable. I tried: $myStr = "The string I want to set"; $fp = fopen("myPage.html", "r"); $data = fread($fp, 100000); $data = '<script type="text/javascript">var myVar=' . $myStr .';</script>' . $data; This did not work the variable was undefined. I am new to PHP so any help with the right way to do this would be great. Thanks John Link to comment https://forums.phpfreaks.com/topic/194660-loading-an-html-page-from-php-and-setting-a-javascript-variable/ Share on other sites More sharing options...
schilly Posted March 9, 2010 Share Posted March 9, 2010 change myPage.html to myPage.php. now in the current script set $myStr = to whatever you want above the include statement. Now in myPage.php change this: <script type="text/javascript">var myVar='<?php echo $myStr; ?>';</script> Now when you include the page it will insert that variable that you set. Make sense? Link to comment https://forums.phpfreaks.com/topic/194660-loading-an-html-page-from-php-and-setting-a-javascript-variable/#findComment-1023759 Share on other sites More sharing options...
mattal999 Posted March 9, 2010 Share Posted March 9, 2010 Simply put, you need to wrap the code in the javascript with quotes. $data = '<script type="text/javascript">var myVar="' . $myStr .'";</script>' . $data; Link to comment https://forums.phpfreaks.com/topic/194660-loading-an-html-page-from-php-and-setting-a-javascript-variable/#findComment-1023761 Share on other sites More sharing options...
jrg23y Posted March 9, 2010 Author Share Posted March 9, 2010 let's say I do change the .html to .php. do I still need to read the file in using fread? I still don't see how the page will have access to the $myString variable you are suggesting? thanks John Link to comment https://forums.phpfreaks.com/topic/194660-loading-an-html-page-from-php-and-setting-a-javascript-variable/#findComment-1023797 Share on other sites More sharing options...
jrg23y Posted March 9, 2010 Author Share Posted March 9, 2010 putting the " into the javascript command worked thanks mattal999!!! Link to comment https://forums.phpfreaks.com/topic/194660-loading-an-html-page-from-php-and-setting-a-javascript-variable/#findComment-1023801 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.