PHP in External Javascript File

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

PHP in External Javascript File

Post by spacebiscuit »

Hi,

Is it possible to reference php variables in an external javascript file? If I paste the javascript directly into my html page I can, but when I place the code into the file the php is not being parsed.

Many thanks in advance,

Rob.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP in External Javascript File

Post by McInfo »

Solution 1: Echo the PHP variables into JavaScript variables in a <script> block in the main script. Write your external JavaScript to access those JavaScript variables.

Solution 2: Use PHP session variables. They will be available to the external JavaScript because it is requested after the main page is returned. The JavaScript file must be parsed by PHP.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Thu Jun 17, 2010 1:42 pm, edited 1 time in total.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

Thanks for the reply.

i think the key here is, liek you say, the Javascript must be paresed by the PHP - but it is not. What I have done is take a sction of Javacript which worked perfectly (and contained PHP variables) and put this into an external js file. But, now instead of echoing the php variable it does the following to the link I am trying to create:

Code: Select all

http://www.mydomainr.com/index.php?id=<? echo $_SESSION[var1]?>
So by placing the working code into the external file it results in the PHP not parsing the javascript.

Any ideas?

Thanks,

Rob.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: PHP in External Javascript File

Post by Apollo »

robburne wrote:What I have done is take a sction of Javacript which worked perfectly (and contained PHP variables) and put this into an external js file.
I bet your webserver does not PHP-parse .js files.

Remember, if you include a .js file somewhere, your browser just makes a separate request for that .js file. Unless your server is configured to also parse .js files (or any file) with PHP, it will just send the .js contents directly. Try renaming the .js to .php, that should help :)
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

As suggested I put the javacript into a php file. I then tried 'include' and 'require' - but rather than executing the code, the raw javascript displays as text at the top of the page...

Rob.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: PHP in External Javascript File

Post by Apollo »

robburne wrote:As suggested I put the javacript into a php file. I then tried 'include' and 'require' - but rather than executing the code, the raw javascript displays as text at the top of the page...
There's no point in including or requiring (from PHP) a file containing javascript. You want to include that in HTML, not in PHP.

Try this:

test.html

Code: Select all

<html><head><script type="text/javascript" src="script.php"></script></head><body onload="Hello()"></body><html>
script.php

Code: Select all

<?php print('function Hello() { alert("Hello dear visitor from IP-address '.$_SERVER['REMOTE_ADDR'].'"); }'); ?>
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

Thanks for the reply Apollo.

I did as you suggested but the variables are stil not being assigned. My javascript was not orginally a function, so I tried placing it inside one but then the code does not execute properly.

maybe what I am trying to do is not possible?

Rob.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: PHP in External Javascript File

Post by Apollo »

Remember that the javascript file is downloaded by the browser through a separate request. Any PHP variables you may have in your main php do not automatically exist in the js php, the latter is not included by PHP but at HTML level (i.e. client side). Just like any variable in a.php would not exist in b.php if you call them separately.

Perhaps you can use sessions for what you're trying to achieve. Or put a short example here of exactly what you're doing, maybe we can help.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP in External Javascript File

Post by McInfo »

Rob, please post your code. It is much easier to debug if we don't have to guess what the code looks like.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Thu Jun 17, 2010 1:43 pm, edited 1 time in total.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

Ok here is the head section of my HTML. The function 'get_currentissue' returns an integer and works correctly. This and the database connection function are in the routines.php file.

Code: Select all

 
<?
session_start();
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
<title>My Page</title>
 
<?
require '../routines.php';
 
$connection=db_connecT('my_db');
$_SESSION[current]=get_currentissue();
?>
 
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
 
<script type="text/javascript" src="current_issue.php"></script>
 
</head>
Here is the first 6 lines of PHP/Javacript which reference the php variables:

Code: Select all

var fadeimages=new Array()
//SET IMAGE PATHS. Extend or contract array as needed
fadeimages[0]=["/covers/images/thumbs/frontcoverwebthumb.jpg", "/covers/index.php?id=<? print_r($_SESSION[current]); ?>", ""] //plain image syntax
fadeimages[1]=["/covers/images/thumbs/backcoverwebthumb.jpg", "/covers/index.php?id=<? print_r($_SESSION[current]); ?>", ""] //image with link syntax
Does this help?

Thanks,

Rob.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP in External Javascript File

Post by McInfo »

session_start() must be called before using the $_SESSION array. That means that you need to add session_start() to the JavaScript file because that file is served from a separate request.

Use something other than print_r() to print the variables: echo, print, or printf().

Before using the session variables, check that they exist with isset() or array_key_exists() to avoid an undefined index error.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Thu Jun 17, 2010 1:44 pm, edited 1 time in total.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

Thanks for the reply.

As advised I added the session start to the beginning of the javascript:

Code: Select all

<?
session_start();
?>
 
var fadeimages=new Array()
However now the javacript does not execute....

Rob.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP in External Javascript File

Post by McInfo »

Here is a basic example.

example.php

Code: Select all

<?php
session_start();
$_SESSION['time'] = date('Y-m-d H:i:s');
?>
<html>
    <head>
        <title>PHP in External JS</title>
        <script type="text/javascript" src="example.js.php"></script>
    </head>
    <body>
        <p>You should have seen an alert with the server time.</p>
    </body>
</html>
example.js.php

Code: Select all

<?php
session_start();
$text = isset($_SESSION['time']) ? $_SESSION['time'] : '';
?>
alert('<?php echo $text; ?>');
robburne wrote:However now the javacript does not execute....
It's nearly impossible to debug invisible code.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Thu Jun 17, 2010 1:45 pm, edited 1 time in total.
spacebiscuit
Forum Contributor
Posts: 390
Joined: Mon Mar 07, 2005 3:20 pm

Re: PHP in External Javascript File

Post by spacebiscuit »

Ok here is my code in full again, I don't think the problem has anything to do with sessions though, the javacript is simply not being executed when contained in the php file. Consider the following:

Code: Select all

 
<?
session_start();
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home Page</title>
 
<?
 
require '../routines.php';
 
$connection=db_connecT('mydb');
$_SESSION[current]=get_current();
 
?>
 
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
 
<script language="javascript" src="/liveclock.js"></script>
<script language="text/javascript" src="current_issue.php"></script>
 
</head>
Then later on this page I call the javascript as follows:

Code: Select all

<script type="text/javascript">
    new fadeshow()
   </script>
The current_issue.php file

Code: Select all

<?php
session_start();
$text = isset($_SESSION['time']) ? $_SESSION['time'] : '';
?>
 
function fadeshow(){
alert('Testing');
}


As you can see the javascript should simply output 'Testing' to the screen but when I call the the page it is blank.

Rob.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP in External Javascript File

Post by McInfo »

Code: Select all

language="text/javascript"
should be

Code: Select all

type="text/javascript"

Code: Select all

$_SESSION[current]
should be

Code: Select all

$_SESSION['current']
Edit: This post was recovered from search engine cache.
Last edited by McInfo on Thu Jun 17, 2010 1:45 pm, edited 1 time in total.
Post Reply