Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
 
extension matters. admin.js.php –  Mathletics Jan 17 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. –  Beetroot-Beetroot Jan 17 at 21:20
1  

2 Answers

up vote 4 down vote accepted

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;
share|improve this answer
 
In admin.php (with .php), do i need to use <script></script> ? –  Sébastien Gicquel Jan 17 at 21:21
1  
Nope, you would use it like a normal js file with php in it –  Ryan Naddy Jan 17 at 21:23
 
Would $date still be set? –  danronmoon Jan 17 at 21:25
 
depends on where date comes from –  Ryan Naddy Jan 17 at 21:26
1  
So in that case, $date won't work unless the query is in the javascript file. –  Ryan Naddy Jan 17 at 21:32
show 1 more comment

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.