tags:

views:

114

answers:

5

i need to have some php code inside javascript

      <script ...>

        <?php
        echo " ... ";
        ?>

       </script>

but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?

+7  A: 

That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.

Cory Petosky
+3  A: 

your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX

Paul Creasey
+5  A: 

Just for clarification, this is what will happen

index.php

<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>

output html in browser

<script type="text/javascript">
alert('hello!');
</script>

If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.

karoberts
+2  A: 

There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:

file javascript.js.php

<?php
    header('Content-Type: text/javascript');
?>

// javascript code here

function PrintTime()
{
   alert("The time is " + <?php echo json_encode(time()); ?>);
}

Now, include it on the HTML page using normal script tags:

<script type="text/javascript" src="/url/to/javascript.js.php"></script>

The server will process the PHP file, and return javascript from it.

gahooa
Yes, badly worded question.
OIS
Note that it is KEY to have the file named as .php - otherwise, the server will not process the <?php directives inside.
Alex
+2  A: 

You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.

It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:

<?php $variable="its me"; ?> 

<script> 
   alert('<?php print($variable)?>') 
</script>

The output passed to the client is:

<script>
    alert('its me')
</script>

What are you trying to accomplish and maybe we can help you come up with a better solution?

John Swaringen
Great answer. To the point.
Josef Sábl
However if `$variable` has a backslash or apostrophe in, you're in trouble! Use `json_encode` to correctly output a JavaScript literal, preferably with `JSON_HEX_TAG` option to avoid problems where your string contains the text `</script>`...
bobince
True bobince hadn't thought of that.
John Swaringen