0

i have a date entry in yyyy-mm-dd format in mysql database. Using php i could get the date value

$row = $myresult['date'];

now i wish to alert this value in javascript

so i tried

var temp_date = <?php echo($row)?>;
alert (temp_date);

but that didn't work for me. The problem i feel i am facing is to maintain the string format of the datestring, which seems to be getting lost when used in javascript. Any help?

asked Aug 3, 2009 at 14:30
1
  • As the fifth in a row to provide the very same answer allow me to withdraw mine. Commented Aug 3, 2009 at 14:36

6 Answers 6

4

String literals are sorrounded by double or single quotes in JavaScript:

var temp_date = "<?php echo($row)?>";
alert (temp_date);
answered Aug 3, 2009 at 14:33
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, i was using VSPhp as the editor and it was reporting a syntax error when i typed the line, that made me wonder if my approach was right. It worked like a charm!
1

This answer originally was a quasi exact copy of the other four first.

If you need the date information as such, you could use Unix timestamps:

SELECT UNIX_TIMESTAMP(timefield) AS timestamp WHERE id = 1;

then just echo it in PHP into this JS snippet:

var mydate = new Date(<?php echo $row['timestamp']*1000; ?>);

You don't need quotes here, since you echo a number. This allows for, e.g.,

alert (mydate.getDate());

and the such.

Cheers,

answered Aug 3, 2009 at 14:35

Comments

1

Use json_encode(). This will turn PHP variables into valid javascript, so you don't have to worry about quoting/escaping etc.

var temp_date = <?php echo json_encode($row); ?>;
alert (temp_date);
answered Aug 3, 2009 at 14:33

Comments

0

You have to add quotes to your JavaScript variable assignation:

var temp_date = '<?php echo($row)?>';
alert (temp_date);
answered Aug 3, 2009 at 14:32

Comments

0
var temp_date = '<?php echo($row)?>';
alert (temp_date);

Add quotes. Otherwise it will error because strings without quotes are troublesome.

answered Aug 3, 2009 at 14:32

Comments

-1

.php

$smarty->assign("profile_date",date("Y/m/d"));

.tpl

var NowDate=new Date("{/literal}{$profile_date}{literal}");
Taryn
249k57 gold badges375 silver badges409 bronze badges
answered May 6, 2012 at 10:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.