Pass PHP Variable To JavaScript And Use Alert To Display

I am attempting the below to pass the value in my php variable to JavaScript, but I never have the alert display on screen. What is the proper way to do such?

PHP

<?php  $date = '20170101'; ?>

JavaScript

var datestring = <? php echo $date; ?>;
var year = datestring.substring(0,4);
alert(year);

Fiddle:

https://jsfiddle.net/3ed6opj3/

The desired result that I want to display in the alert is 2017 - the answers below to this point have all been showing <? p

Upvotes: 1

Views: 89

Answers (2)

David
David

Reputation: 609

You need to add quotes

<?php echo "\"".$date."\""; ?>;

Upvotes: 0

Komang Suryadana
Komang Suryadana

Reputation: 696

You have to add " on between the php script

var datestring = "<?php echo $date; ?>";

Upvotes: 1

Related Questions