I am trying to pass php variables into javascript. I have a count down in my website(I have more than one actually). I am calculating the time through my database and I have a result, something like this:
$month = 02;
$days = 05;
$hours 01;
I have this javascript in the place a want to appear the count down
<script type="application/javascript">
var month_user = <?php echo $month_user; ?>;
var days_user = <?php echo $days_user; ?>;
var tot_hours = <?php echo $tot_hours; ?>;
var myCountdown1 = new Countdown({
year : 2014,
month : month_user,
day : days_user,
hour : tot_hours,
ampm : "pm",
minute : 0,
second : 0,
width: 173,
height: 35,
rangeHi:"day",
style:"flip" // <- no comma on last item!
});
</script>
So, my count down must show 1 hour left.. But it does not work.. I am not very good in javascript..
Can anyone help with this?
I tried to use something like this that I saw in another post here,
var month_user = ; var days_user = ; var tot_hours = ;
but still nothing... How can I pass my php values into this script?? thanks in advance
3 Answers 3
Just enclose the php code in " ", and it will work. Try below :
<script type="application/javascript">
var month_user = "<?php echo $month_user; ?>";
var days_user = "<?php echo $days_user; ?>";
var tot_hours = "<?php echo $tot_hours; ?>";
var myCountdown1 = new Countdown({
year : 2014,
month : month_user,
day : days_user,
hour : tot_hours,
ampm : "pm",
minute : 0,
second : 0,
width: 173,
height: 35,
rangeHi:"day",
style:"flip" // <- no comma on last item!
});
</script>
If still it is not working then try them as below :
<script type="application/javascript">
var month_user = "<?php echo $month_user; ?>";
var days_user = "<?php echo $days_user; ?>";
var tot_hours = "<?php echo $tot_hours; ?>";
</script>
And after that you can place the remaining code in an other script tag.
This method is effective and it create global JS variables for you, which then you can use in all of your JS files included below that declaration.
Comments
Try this :
$_SESSION['days']= '05'
and
...
day : <?$_SESSION['days']?>,
...
Comments
They always should be quoted because they are not defined variables.
var month_user = '<?php echo $month_user; ?>';
var days_user = '<?php echo $days_user; ?>';
var tot_hours = '<?php echo $tot_hours; ?>';
var month_user = <?php echo $month_user; ?>;? Also, be sure this is being run in a .php file, not a .js file. If that's not possible, you could do something like echo the PHP vars out into separate<meta>tags and use JS to grab those values.