tags:

views:

56

answers:

2

I have a website where I am including a php library file and a javascript library file. I have condensed the problem to the following files:

index.php

<?php
  include('constants.php');
?>
<html>
  <head>
    <script type="text/javascript" src="lib.js"></script>
  </head>
  <body onload="javascript:show_const_1('<?php echo(CONST_TEXT); ?>');
                           show_const_2();">
    Some text here
  </body>
</html>

constants.php

<?php
  define('CONST_TEXT', 'Hello World');
?>

lib.js

function show_const_1(string)
{
  alert(string);
}

function show_const_2()
{
  alert('<?php echo(CONST_TEXT); ?>');
}

The result is that when the page loads I get two message boxes. The first says "Hello World" and the second says "<?php echo(CONST_TEXT); ?>". The first javascript method does what I want it to, but I will be using the function in many places across the site and so ideally I don't want to have to pass the constant as a parameter every time.

Is there a good way to rearrange the code to make the second javascript method work?

+2  A: 

The method body inside alert() is not interpreted by PHP (it's interpreted by Javascript), so you can't put PHP tag in it

Ngu Soon Hui
The following works fine in a php file: alert('<?php echo 123; ?>');
tttppp
+4  A: 

The simple answer is rename "lib.js" to "lib.php".

You should also add

header('Content-type: text/javascript');

to the top of the file.

Incidentally, you should us json_encode() to output text to javascript:

alert(<?php echo json_encode(CONST_TEXT); ?>);

And "javascript:" doesn't belong in event attributes (which are kindof outdated anyway):

<body onload="doSomething();">
Greg
The MIME type of JavaScript is now *application/javascript*.
Gumbo
Lots of helpful comments - thanks. Php is now being executed in lib.php, but the constant CONST_TEXT does not appear to be defined in lib.php.The php <?php echo CONST_TEXT; ?> results in the string "CONST_TEXT" (as opposed to "Hello World").
tttppp
You probably need to include() whichever file you define CONST_TEXT in
Greg
Ok - thanks :-)
tttppp