Reputation: 147
I am retrieving a Facebook Page Like count via a PHP function like this:
<?php
function fbLikeCount($id,$appid,$appsecret){
$json_url ='https://graph.facebook.com/'.$id.'?access_token='.$appid.'|'.$appsecret.'&fields=likes';
$json = file_get_contents($json_url);
$json_output = json_decode($json);
if($json_output->likes){
return $likes = $json_output->likes;
}else{
return 0;
}
}
?>
Then, I am able to echo this out no problem like this:
<?php
echo number_format(fbLikeCount('companynamegoeshere','XXXXXXXXXXXX','XXXXXXXXXXX'));
?>
But, I am using a JavaScript function to do this animation for where teh number is displayed on the page, like this:
<script>
$({someValue: 0}).animate({someValue: 450700}, {
duration: 3000,
easing: 'swing',
step: function () {
$('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
},
complete:function(){
$('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
}
});
</script>
Where that 450700 is in the JS code is where I need to put the PHP echo'ed number. Is it even possible to put a PHP echo (if I make it a variable first?) into the JS.
I've tried many, many things and hitting a brick wall. Any help is greatly appreciated.
thanks!
Upvotes: -1
Views: 3723
Reputation: 15489
To modify @Pedro Lobito's answer - you echo the value inside the js as follows:
<?php
$number = "1234";
?>
<script>
$({someValue: 0}).animate({someValue: <?php echo"$number";?>}, {
duration: 3000,
...
or alternatively:
<?php
$number = "1234";
?>
<script>
var testValue = <?php echo"$number";?>;
$({someValue: 0}).animate({someValue: testValue}, {
duration: 3000,
...
or even
<input type="hidden" name="testInput" value="<?php echo"$number";?>" />
<script>
var testValue = $('[name=testInput]').val();
$({someValue: 0}).animate({someValue: testValue}, {
duration: 3000,
...
or a hidden div / span - but move the display:none to the external CSS sheet
<span style="display:none" id="testSpan"><?php echo"$number";?></span>
<script>
var testValue = $('#testSpan').text();
$({someValue: 0}).animate({someValue: testValue}, {
duration: 3000,
...
Upvotes: 0
Reputation: 98871
You can add php
code inside JavaScript, if the JavaScript code is on a php page, but I prefer using the heredoc syntax, i.e.:
somefile.php
<?php
$number = "1234";
echo <<< LOB
<script>
$({someValue: 0}).animate({someValue: {$number}, {
duration: 3000,
easing: 'swing',
step: function () {
$('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
},
complete:function(){
$('#facebookCount').text(commaSeparateNumber(Math.round(this.someValue)));
}
});
</script>
LOB;
?>
Upvotes: 0
Reputation: 2257
You can put PHP tags inside of the javascript if the javascript is in the php file. But honestly, you'd be better off creating an element that is hidden, echoing the data you need in that, and then just using javascript to get the value/innerHTML of that element.
Upvotes: 3