0

I want to use a php variable in .js file. Is this possible that we can call a php variable in .js file. what I have done for this problem

I have .php file where i created var

$domainname = "wwww.google.com ";

In second file .php

<?php  header("Content-type: application/javascript"); ?>
<script> 
var DomainName = <?php echo $GLOBALS['SettingDomainName'];?> 
</script>

and finally I want to call this var in js

<script src="public_https/test.js"></script>
alert(DomainName);

I got this message :

SyntaxError: syntax error
<script src="public_https/test.js"></script>

4 Answers4

3

Use json_encode function which returns JSON representation of a variable which can be used inside JavaScript as-is:

<?php
$domainname = "www.google.com";
?>
<script>
var DomainName = <?php echo json_encode($domainname); ?>;
</script>

Note: no quotes. This function works for all types of variable: string, integer, float, boolean, null and etc.

Salman A
  • 262,204
  • 82
  • 430
  • 521
0
<script> 
var DomainName = "<?php echo $GLOBALS['SettingDomainName'];?>";
</script>
test
  • 464
  • 5
  • 14
0
<input type="hidden" id="domain_name" value="<?php echo $GLOBALS['SettingDomainName']; ?>">

JsFile:

var DomainName= document.getElementById('domain_name');
Karthik Keyan
  • 424
  • 4
  • 15
0

What about we hide your variable in a hidden box using php

 $domainname = "wwww.google.com ";

<input type="hidden" value=" <?php  echo "$domainname"; ?>" id="mydomain">

Then we fetch it using js or jquery

<script>
     var domain=$('#mydomain').val();
</script>
jonah
  • 213
  • 4
  • 16