1

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

1
  • This is giving me <? p as the alert, I want it to show 2017. Commented Jul 18, 2017 at 0:49

2 Answers 2

1

You have to add " on between the php script

var datestring = "<?php echo $date; ?>";
Sign up to request clarification or add additional context in comments.

3 Comments

That produces <? p - my desired result is 2017
try again on the up code i already edited, previously already space between <? and php.
Yeah on jsfiddle cant change to php language, you can running on your local machine for trying
0

You need to add quotes

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.