3

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?

0

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can we are able to do <?php echo base_url(); ?> in .js file?
1

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;

Comments

1

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.

2 Comments

application/x-javascript? application/javascript has been standard for years.
Thanks for all the feedback guys! Went with the solution suggested by Madmartigan in the finish, works a treat :)
0

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.

2 Comments

Via AJAX? That's pretty awful - would you do that?
No I wouldn't, but it is possible. I would do the last point.
0

Heredoc worked for me today:

<?php
echo <<<ANYNAME

<script LANGUAGE="JavaScript" type="text/javascript">
<!--
// code ...
var myLatlng = new google.maps.LatLng($lat, $lon);
// code cont. ...
//-->
</script>

ANYNAME;
?>

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

php variable in html no other way then: <?php echo $var; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.