Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a PHP Variable in external JS file [duplicate]

I've read lots of thread on here but I am still unable to get a variable passed from PHP to an external JS file and wondered if someone could assist?

In my PHP file I have the following;

<script type="text/javascript">
var pass_this_variable = <?php $company['website']; ?>;
</script>

<script type="text/javascript" src="/js/track.js"></script>

In the JS file I have the following;

document.write('<IFRAME SRC="$company['website']" WIDTH="300" HEIGHT="400"></IFRAME>');

What I am trying to achieve is an IFRAME be opened and populated with what is contained within $company['website']. I know I can just use IFRAME directly in the PHP file, but this isn't what I have been tasked with for my homework. When I do use IFRAME directly in the PHP file it works fine, and if I specify a static URL in the JS file such as http://www.google.com this also works fine.

Can anyone assist? Thanks


EDIT:

Thanks for the answers so far, however I'm still unable to get it working :(

The frame that I have in track.php (or track.js) won't load the url thats specified in $company['website'], yet if I change it to http://www.google.com its working fine. For some reason the $company['website'] value isn't being passed :(

like image 493
Petra Avatar asked May 14 '11 09:05

Petra


2 Answers

if you want your external javascript to be dynamic you can make it a php file and give the correct header, example:

<script type="text/javascript" src="/js/track.php"></script>

track.php

<?php
// javascript generator
Header("content-type: application/x-javascript");
?>
document.write('<IFRAME SRC="<?php echo $company['website'] ?>" WIDTH="300" HEIGHT="400"></IFRAME>');
like image 167
Ibu Avatar answered Nov 03 '22 00:11

Ibu


PHP file (don't forget echo and quoting):

<script type="text/javascript">
var pass_this_variable = '<?php echo $company['website']; ?>';
</script>

<script type="text/javascript" src="/js/track.js"></script>

JS file (use pass_this_variable instead):

document.write('<IFRAME SRC="'+pass_this_variable+'" WIDTH="300" HEIGHT="400"></IFRAME>');
like image 45
AndersTornkvist Avatar answered Nov 03 '22 00:11

AndersTornkvist