Cronin O'M
Cronin O'M

Reputation: 692

Inserting PHP variable value in Javascript file

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?

Upvotes: 3

Views: 3426

Answers (5)

darekk
darekk

Reputation: 81

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; ?>

Upvotes: 0

moranjk
moranjk

Reputation: 151

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.

Upvotes: 1

Armin
Armin

Reputation: 15938

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.

Upvotes: 1

ChrisW
ChrisW

Reputation: 5068

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;

Upvotes: 1

No Results Found
No Results Found

Reputation: 102735

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.

Upvotes: 5

Related Questions