Barry Corrigan
Barry Corrigan

Reputation: 95

Using PHP inside a JavaScript function

I'm using the jQuery countdown plugin to have a timer on my website http://keith-wood.name/countdownRef.html

I am using an API from SportsRadar to list some fixtures that has the dates on

<?php echo date("Y/d/m/ - H:i", strtotime($nextMatch['KickOff'])); ?>

this will output as 23/04/2015 - 20:00

In the Countdown plugin their function is the following

<script>
    var matchDay = new Date();
    matchDay = new Date(2015, 04-1, 22, 20, 0, 0);
</script>

I'm just looking to know how would I add that PHP echo into that JavaScript function? Is it even possible?

Upvotes: 1

Views: 605

Answers (4)

Barry Corrigan
Barry Corrigan

Reputation: 95

By doing this it worked fine

<script>
var matchDay = new Date();
    matchDay = new Date('<?php echo date("Y", strtotime($nextMatch['KickOff'])); ?>', '<?php echo date("m", strtotime($nextMatch['KickOff'])); ?>'-1, '<?php echo date("d", strtotime($nextMatch['KickOff'])); ?>', '<?php echo date("H", strtotime($nextMatch['KickOff'])); ?>','<?php echo date("i", strtotime($nextMatch['KickOff'])); ?>');
</script>

Upvotes: 0

Danilo
Danilo

Reputation: 2686

PHP function strtotime() gives you the number of seconds since 1970. You can use this information to initialize a javascript Date object. However, javascript expects the number of milliseconds since 1970, thus you ought to multiply the value by 1000:

<script>
    var matchDay = new Date(<?php echo strtotime($nextMatch['KickOff'])*1000;?>);
</script>

Now you know when the match will take place (in javascript), and you can use it to initialize a countdown or whatever else you want to do with this information.

Upvotes: 1

jcubic
jcubic

Reputation: 66478

You an use something like:

var matchDay = new Date(<?php $time = strtotime($nextMatch['KickOff']); 
echo date("Y", $time) . "," . date("m", $time) . "," .
    date("m", $time) . "," . date("H", $time) . "," .
    date("i", $time);
?>, 0, 0);

Or you an parse date in JavaScript

Upvotes: 1

Muhammad Abdul-Rahim
Muhammad Abdul-Rahim

Reputation: 2010

PHP is server-side and will run once. JS is much unlike this. If you need the JS to call a PHP script, consider making an AJAX call. Looking at your goals, however, this seems a tad unnecessary. If all you want is to echo data, you can use JS to update HTML elements on the page instead. That I believe would be the simple solution for your requirements.

Upvotes: 0

Related Questions