tttppp
tttppp

Reputation: 8183

Organising code that includes php and javascript files

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?

Upvotes: 0

Views: 154

Answers (2)

Greg
Greg

Reputation: 321588

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();">

Upvotes: 4

Graviton
Graviton

Reputation: 83254

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

Upvotes: 2

Related Questions