0

I'm a bit confuse on passing PHP variables that contains date on an onclick attribute of a button, for example.. (for some reason, I put the button inside an echo)

<?php
$date = date("F-d-Y", "2015-07-24"); //to convert the string 2015-07-24 to date with an specific format
echo "<button onclick = 'goToThisJSMethod(".$date.")'> Pass </button>";
?>

on the javascript part wherein goToThisJSMethod written.

function goToThisJSMethod(dateRec){
 alert (dateRec);
} 

The syntax above results nothing and the alert box didn't appear

I tried changing the above code, I alter the parameter that will be passed on PHP, instead of using $date variable, I used the exact string of the date to be the parameter and change the javascript like this:

function goToThisJSMethod(dateRec){
    var date = new Date(dateRec);
    alert(date.getMonth()+1 " " + date.getDate() + " " + date.getFullYear());
}

Yes there's a result with this but then again, it returns a default date of 1/1/1970. What should I do regarding with this problem?

1 Answer 1

1

The biggest problem is the second argument to date() has to be a timestamp, so you need to use strtotime. You'll always get "January-01-1970" because you're passing it a string where it needs a timestamp.

You probably also need quotes around your string, as below. Check the rendered HTML in the browser to see.

<?php
$date = date("F-d-Y", strtotime("2015-07-24")); 
echo "<button onclick=\"goToThisJSMethod('{$date}')\"> Pass </button>";
?>

I converted your html to use " and PHP to use variable interpolation.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome @NielSinel :) Don't forget to mark as answer :)

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.