0

Usually, when i need to use some php in javascript code, i use to put the code into the head like this :

<script>
    $(function() {

    $("input#datepicker").val('<?php echo $date ?>');
});
</script>

This way, i can use some php variables in javascript code. It works fine.

Do you know how to do this if i want to put all javascript code in an external js file :

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

Maybe it doesn't matter at all. But i use to code in an external js file and and i'm wondering if it's possible to do that.

3
  • extension matters. admin.js.php Commented Jan 17, 2013 at 21:20
  • 1
    I wanted to do this once and was persuaded not to. The issues are (a) having to put .js files through the PHP parser, and (b) needing to adopt measures to avoid caching. Commented Jan 17, 2013 at 21:20
  • 1
    stackoverflow.com/questions/11206599/… Commented Jan 17, 2013 at 21:21

2 Answers 2

4

You would need to make the js file a php file.

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

If you still want to keep the js extension, you need to do a rewrite for your webserver.

js/admin.php

<?php
header("content-type: text/javascript");
?>
$(function() {
    $("input#datepicker").val('<?php echo $date ?>');
});

if you want the js extension here is an example rewrite.

Nginx

rewrite /js/admin.js /js/admin.php;

Apache

RewriteEngine On
RewriteBase /
rewrite /js/admin.js /js/admin.php;
Sign up to request clarification or add additional context in comments.

5 Comments

In admin.php (with .php), do i need to use <script></script> ?
Nope, you would use it like a normal js file with php in it
depends on where date comes from
$date comes from a query from database : $date = $data['date_publication'];
So in that case, $date won't work unless the query is in the javascript file.
1

It's better to cache your js into client browser and just send the variable to client. if you serve all js as new response. think about bandwidth and another request to your web server.

<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript">
    var myVar = <?php echo json_encode($myVar); ?>;

    myAdminFunction(myVar);
</script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.