Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a JavaScript file which has a hard coded BASEURL variable, this value is then used by other functions in the file. I would like for this url value to be set dynamically so that I don't need to manually change it for different installs. Is it possible to insert a PHP variable value into a JavaScript file?

share|improve this question
    
Yes, it is possible. –  Aurelio De Rosa Jan 17 '12 at 11:14
add comment

4 Answers

up vote 5 down vote accepted

Rather than try to mix PHP into javascript files, here's what I do in the HTML template:

<head>
    <script>
        var BASEURL = "<?php echo base_url(); ?>";
    </script>
    <script src="/path/to/my_script1.js"></script>
    <script src="/path/to/my_script2.js"></script>
</head>

This sets the variable and allows all your embedded scripts to access it. base_url() would be replaced by whatever method you use to fetch the base url with PHP.

share|improve this answer
    
Can we are able to do <?php echo base_url(); ?> in .js file? –  Somnath Muluk Feb 13 '12 at 11:13
add comment

Suppose you have a JS file written on the fly by PHP; file1.php

<?php
  header('Content-Type: application/javascript');
  $var = $_GET['var1'];
  echo "jsvar = ".$var.";";
?>

The client-side source code of file1.php?var1=10 will then be

jsvar=10;
share|improve this answer
add comment

There exists several ways:

  1. Load the baseurl via AJAX, but maybe this is to slow, maybe you need it earlier.

  2. let the javascript file running through the php parser. Then you could use inline echos.

  3. The most convenient and easiest way, is to make a <script>var baseurl = '...';</script> in the html/php output of your page.

share|improve this answer
    
Via AJAX? That's pretty awful - would you do that? –  Wesley Murch Jan 17 '12 at 11:24
    
No I wouldn't, but it is possible. I would do the last point. –  Armin Jan 17 '12 at 11:31
add comment

You will need to make your file a php file, not a js file. From there you can include any PHP tags in the file to work your dynamic magic. The key to make this whole thing work is in the headers, which you will need to set like so:

<?php
    Header("content-type: application/x-javascript");
      echo 'var js_var = ' . $php_var;
?>
alert (js_var);

This technique can be used to for CSS files as well.

share|improve this answer
    
application/x-javascript? application/javascript has been standard for years. –  Quentin Jan 17 '12 at 11:24
1  
Thanks for all the feedback guys! Went with the solution suggested by Madmartigan in the finish, works a treat :) –  Cronin O'M Jan 17 '12 at 13:15
add comment

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.