1

I want to know if I can include php scripts in javascript[1] the same way it can be done in html[2]

server.php:
<?php
    echo 'hello World';
?>

client.js (or client.php if necessary):

function foo() {
    var i = <?php include('server.php'); ?>
    console.log( i );
}

If it can be done, and if client.php must be used instead, I would really appreciate a minimal example with index.html/index.php as well, since I would like to see how I would include client now that it is a php file and not javascript

Community
  • 1
  • 1
puk
  • 16,318
  • 29
  • 119
  • 199
  • Server Side Includes just takes the output of the "included" PHP file. To do the same with JavaScript, use AJAX. Is jQuery possible in your environment? – Shadow The GPT Wizard Nov 22 '11 at 13:36
  • 1
    "client.js (or client.php if necessary)" -> yes, I think... You need to enquote your string like `var i = '';` – rap-2-h Nov 22 '11 at 13:36

6 Answers6

4

You can use output buffering to achieve something similar, although it's not possible to directly embed PHP code in JS.

Example:

server.php

<?php
    echo 'hello World';
?>

client.php - (.php extension enables the ability to parse PHP tags, but really outputs JS)

<?php
header("Content-type: application/x-javascript"); // Or 'text/javascript'
ob_start();
include( 'server.php');
$i = ob_get_contents();
ob_end_clean();
?>
function foo() {
    var i = '<?= json_encode( $i); ?>';
    console.log( i );
}

Edit: If the server.php file will only return a simple string, then you can modify your code for client.php. Notice how I said "return" instead of output - If your server.php outputs anything, it will be sent to the browser as output (not what you want). Alternatively, you can set a variable in server.php which gets outputted in client.php, or encapsulate your code in a function:

server.php

<?php
function js_output()
{
    return 'hello world';
}
?>

client.php

<?php
header("Content-type: application/x-javascript"); // Or 'text/javascript'
?>
function foo() {
    var i = '<?php include( 'server.php'); echo addslashes( js_output()); ?>';
    console.log( i );
}

Note: You may also want to add a call to html_entities or htmlspecialchars.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • I am looking to execute the code serverside and embed the returned value – puk Nov 22 '11 at 13:59
  • That is exactly what will happen - When the client requests `client.php`, the server will execute the PHP block at the top of _client.php_, which includes the _server.php_ file, executes it, stores its output into a variable named `$i`, and then embeds that value in the JS variable `i` using JSON. – nickb Nov 22 '11 at 14:00
  • It's just that I don't want to go around putting large chunks of php code inside my javascript. Is it not possible to put the php somewhere else, have it return/echo a value and just use `` inside of `client.php` – puk Nov 22 '11 at 14:12
  • It really depends on what your script is outputting - If it's just an integer or a simple string then the above can be simplified. My example will work with any output that is generated by _server.php_. – nickb Nov 22 '11 at 14:14
  • @puk I've added a more simplistic example that will achieve what you're looking for. I should point out that if you do not use output buffering or a function (like I've shown above), your *server.php* cannot output anything, as that output will likely be sent directly to the browser at the time *server.php* is included instead of being embedded into the JS. – nickb Nov 22 '11 at 14:26
  • Thanks for the example. I am getting `SyntaxError: Unexpected token <` I wonder if the fact that I am running suPHP is causing that. – puk Nov 22 '11 at 14:37
  • @puk - Which line is generating that error? I just checked the syntax of my example and it seems correct. – nickb Nov 22 '11 at 14:41
  • let me use your example exactly to be absolutely sure – puk Nov 22 '11 at 14:42
  • 1
    Yes your example works for me too! Thanks, I'll see what I did wrong trying to incorporate it into my example – puk Nov 22 '11 at 14:48
  • Word of caution to anyone using javascriptLint, `/*jsl:ignore*/` and `/*jsl:end*/` don't work and it will register ` – puk Nov 22 '11 at 14:50
  • Would this approach also work if loading via Ajax? That might be my problem here. – puk Nov 22 '11 at 14:56
  • Sure, the file that you request from your AJAX entry point just needs to do something like: `echo js_output();`, unless you're requesting *server.php* from AJAX, which would then require you to use output buffering. – nickb Nov 22 '11 at 15:01
2

It has to be a .php file. You need to set this as the first line in your client.php:

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

Then, you could create the file like that, and just include it, and use it as a regular javascript file. So with the <script> tag, as it is now recognized as JavaScript

Rene Pot
  • 24,681
  • 7
  • 68
  • 92
  • So basically the server is smart enough to realize that it's a '.php' file and the client gets tricked into thinking it's a '.js' file. – puk Nov 22 '11 at 13:39
  • Could you please give me an example I could use in a simple `` scenario – puk Nov 22 '11 at 14:22
2

The easiest thing to do would be to use client.php instead of client.js, since your server will automatically send a .php file through the PHP interpreter. You technically could reconfigure the server to do it to .js files, but I wouldn't recommend it.

The client.php file should include this line before anything is outputted to the user:

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

As for a basic index.html/index.php example:

<html>
<head>
<title>Example</title>
<script type="text/javascript" src="client.php"></script>
</head>
<body>
...
</body>
</html>

Update: example client.php file:

<?php
    header("Content-type: text/javascript"); // This bit must come first!
?>
var i = "<?php echo $somevar; ?>" // This is JavaScript code with some PHP embedded.
Rsaesha
  • 1,104
  • 1
  • 13
  • 25
  • I'm not trying to be ungrateful, but a lot of the responses don't sufficiently dumb it down for me =P for example should I have `` around my entire javascript statements? The `header("Content-type: text/javascript");` comes *after* the `` correct? – puk Nov 22 '11 at 14:24
  • The `header(...);` statement comes directly after the opening ` – Rsaesha Nov 22 '11 at 15:10
2

To embed PHP in a file the server needs to pass it through the PHP parser and it will only do that with files-types it has been told contain PHP markup, i.e. .php files. You could potentially tell the server to parse js-files as well, but I'm not sure if the mime-type would be set correctly. It would also require you to change the server settings. If you call the javascript-file .php the mime-type will definitely be wrong. The most compatible way to do this would be to put the javascript in the html-file (i.e. your .php file). If you want to keep the amount of javascript in your .php files to a minimum you can just put the variable-assignments in the .php file and keep the rest in your javascript file.

server.php:

<script language="javascript">
    var some_var = "<?php echo $SOME_VAR ?>";
</script>

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

client.js:

alert(some_var);

The (global) javascript variable some_var will be set to whatever the PHP variable $SOME_VAR is set to. Don't forget the quotes when setting string values. Also if the PHP code contains errors you could contaminate the javascript code so alot of care has to be taken when doing this.

brainchild
  • 21
  • 1
1

I tested this solution on PHP 5.5.
1. Create a file called myScript.php.

// myScrpt.php content:

<?php 
$fname = "Jason";
$lname = "Kent";
?>
  1. Create a file called test.php.

// test.php content:

<!DOCTYPE html>
<html>
<head>
<title>Include php Script</title>

<script type="text/javascript">
<?php include 'myScript.php'; ?>
</script>

</head>

<h1>The result is:</h1>
<?php
echo "My full name is $fname $lname.";
?>

</body>
</html> 
  1. When you open test.php in a browser, you will get:

My full name is Jason Kent.

Dah Moymy
  • 11
  • 1
0

You cannot have a client load PHP. The only way you can do this is to have on server.php

<html>
    <head>
          <script type="text/javascript">
          function foo() {
             var i = <?php echo 'hello World'; ?>
              console.log( i );
           }
          </script>
    </head>
    <body>
    </body>
</html>

Basically loading the javascript into the body of the page. Or alternatively.

 <html>
    <head>
          <script type="text/javascript">
             var i = <?php echo 'hello World'; ?>
          </script>
          <script type="text/javascript" src="client.js">
    </head>
    <body>
    </body>
</html>

And in client.js

function foo() {
   console.log( i );
}

essentially variable i can be loaded as a global variable on the page

or as another post suggest, masquerade a php file as a js.

  • 1
    This results in the JS code: `var i = hello World;`, which is (obviously) not valid syntax. – nickb Nov 22 '11 at 13:42