₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,110 members, 8,420,394 topics. Date: Thursday, 04 June 2026 at 06:27 PM

Toggle theme

Passing Php Variables To Javascript - Webmasters - Nairaland

Nairaland ForumScience/TechnologyWebmastersPassing Php Variables To Javascript (817 Views)

1 Reply (Go Down)

Passing Php Variables To Javascript by DualCore1(op): 10:02pm On Jun 07, 2010
Anyone has any method he/she uses to accomplish this?

The scenario is I have a php document containing some variables and I need to do some calculations in a seperate javascript file using those php variables. I have already achieved this but I am trying to optimize my codes so i'm looking to know if there's a better way anyone has of doing this.

Here's how I do it.
I use html as the bridge. I include the php document into html and pass the variables into hidden form fields
<input type="hidden" value ="<?php echo $variable1 ?>" id = "variable1" />

In javascript I now get the variable from the hidden field in the html.
var variable1 = parseInt($('#variable1').val());

And then I can do any math I want.

Now imagine crossing about a hundred variables from php to javascript through my kinda bridge! That's too many kids on the bridge!! I know there must be a better way, any ideas?
Re: Passing Php Variables To Javascript by ogzille(m): 11:02pm On Jun 07, 2010
<script language="javascript">var e='<?php echo $variable;?>';</script>
Re: Passing Php Variables To Javascript by kehers(m): 11:05pm On Jun 07, 2010
Hmmm,

Another way I can think of is masking ur php as js and passing the variables to it via GET like this

HTML:
<script type="text/javascript" src="js/js.php?var=value&var2=value2"></script>

JS (js.php):
<?php
header('content-type:application/x-javascript');
foreach($_GET as $k => $v){
  $$k = $v;
}
?>
var variable1 = <?= $var; ?>;
var variable2 = <?= $var2; ?>;

The drawback however, is that it is assumed the variables are already declared before including the js.
Re: Passing Php Variables To Javascript by OmniPotens(m): 2:54am On Jun 08, 2010
I think you can pull some resources from here

www.phpjs.org

I know it will be of great help.
Re: Passing Php Variables To Javascript by DualCore1(op): 5:08am On Jun 08, 2010
Thanks guys smiley
1 Reply

Welcome To Javascript For The Total Non- ProgrammerDhtml Quiz: How Will You Detect If A Browser Support Javascript From Php Code?Session Variables234

10 Steps To Go From Agile To Ultra Lean DevelopmentA Web Developer's Ideal WifeProfessional Webmaster/designer Needed