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>
3
  • does var DomainName = <?php echo $GLOBALS['SettingDomainName'];?>; (added a semicolumn after the php close tag) helps? Commented Jun 18, 2015 at 10:17
  • You dont need to wrap that into script tag and you should make it a string. Commented Jun 18, 2015 at 10:17
  • @Goikiu did you see that funny picture where morphius says that semicolons are optional on javascript? Commented Jun 18, 2015 at 10:18

4 Answers 4

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.

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

1 Comment

Sorry, my bad. You're completely right.
0
<script> 
var DomainName = "<?php echo $GLOBALS['SettingDomainName'];?>";
</script>

Comments

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>

Comments

0
<input type="hidden" id="domain_name" value="<?php echo $GLOBALS['SettingDomainName']; ?>">

JsFile:

var DomainName= document.getElementById('domain_name');

4 Comments

You might want to elaborate on what your answer does. SO exists to teach, not just answer questions. You also need to wrap that echo statement in <?php ?>
@machavity Hi, Updated the answer pls check review it
Better from a code standpoint but still needs some comments on what this does. Compare your answer to the one Salman gave. He talks about his answer some.
@machavity okay, I will try to improve :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.