1

I have a php file as my main page, and I want to pass a php variable to an external js file that is drawn with php. I have several php'd external js files that work fine but are "not" dependent on php from the main page. Some are dependent on JavaScript from the main page, but I want to move away from that. My intentions are to keep the main page clean by limiting the amount of JavaScript on it, by increasing dynamics, and to allow better site management.

Maybe if I understood the natural relationship of external files to the calling page, i dun know. For instance, the code below is some of my current code, and it assumes the external js script, being the php file it is, sees "functions.php" and $sel_entity from the main page. However, it does not seem to work that way. I am guessing maybe functions.php needs to be included in the external file, but no clue with $sel_entity. I am aware I could echo variables to a js variable on the main page, but I need something more dynamic for my plans. Any help here would be great. Thank you!

For instance, the main page is something like:

<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php  $sel_entity = $_GET['entity']; ?>
...//bunches of code 
<script type="text/javascript" src="javascripts/lines.php"></script>

Then the js file lines.php is something like:

<?php
 Header("content-type: application/x-javascript");
  $job_set = get_jobs($_GET['entity']);                     
  while ($job = mysql_fetch_array($job_set)) {
    echo "
        var jobLine";
echo $job["Project_ID"];
echo " = [new google.maps.LatLng(lati, longi),
";
$jobIdCoords = get_jobCoord_by_id($job["Project_ID"]);
echo " new google.maps.LatLng(";
echo $jobIdCoords['lat'] . ", ";
echo $jobIdCoords['long'] . ")]; ";
                    }
  ...// bunches more code
?>  
asobe
  • 15
  • 3

1 Answers1

2

The best way would be to use $_SESSION, but be sure to start the session in the "js" file.

<?php
session_start();
$_SESSION["foo"] = "bar";
?>
<script type="text/javascript" src="javascripts/lines.php"></script>

And then the JS file:

<?php
Header("content-type: application/x-javascript");
session_start();
echo 'var foo = "'.$_SESSION["foo"].'";';
?>
alert(foo);

However, you should be able to also use $_GET like so:

<script type="text/javascript" src="javascripts/lines.php?foo=bar"></script>

And the "JS" file:

<?php
Header("content-type: application/x-javascript");
echo 'var foo = "'.$_GET["foo"].'";';
?>
alert(foo);
TylerH4
  • 463
  • 1
  • 5
  • 12
  • Thank you, it worked great! I can now merge multiple externals. In addition, I did have to include the connection.php and functions.php. – asobe Jun 11 '12 at 00:45
  • No problem! Just be careful with what you are sending. If you are using the $_GET method, the ?foo=bar query is clearly visible in HTML source! This means anyone would be able to change it if they wanted. – TylerH4 Jun 11 '12 at 05:58