0

I know how to code in PHP but admittedly new to Javascript. I am trying to create a link upon collecting the date. When I echo the date from the JS code, it works but adding it inside a link is somehow proving challenging.

<?php  
if ( ! defined( 'ABSPATH' ) ) exit;

$date = '<script type="text/javascript">
var event = new Date();
var options = { year: "numeric", month: "numeric", day: "numeric" };
document.write(event.toLocaleDateString("es-CL", options));
</script>';

echo $date; // 18-11-2021

//Unable to create a link
echo '<a href="/example/'.$date.'"> Today </a>';

?>

Unsure what my code is missing. Thanks

2
  • 1
    This won't work because you try to execute JavaScript code and store the result in PHP. It won't be happening because it runs PHP first (server) then JS (frontend). The solution here is to generate the date and link in JavaScript without PHP. Commented Nov 18, 2021 at 4:59
  • Does this answer your question? What is the difference between client-side and server-side programming? Commented Nov 26, 2021 at 10:44

2 Answers 2

1

You can use like below to get javascript date in link:

<a href="" id="mydate"> Today </a>

<script type="text/javascript">
var event = new Date();
var options = { year: "numeric", month: "numeric", day: "numeric" };
var date=event.toLocaleDateString("es-CL", options);
document.getElementById("mydate").href="/example/"+date;
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to go one day before or after the current date how can I include that?
You can do like: var event = new Date(); event.setDate(event.getDate() + 1);
1

This is how you can achieve it using jquery

Step 1: Add Jquery CDN

Step 2: HTML

<a href="javascript:void(0);" class="test">Test</a>

Step 3: Adding Jquery Code and getting current date time

var currentdate = new Date(); 
var datetime = currentdate.getDate() + "/"
                + (currentdate.getMonth()+1);

$('.test').attr('href',datetime); //this is how you can add to href tag
$('.test').text(datetime) //this is how you can add to text of <a> tag

This is how you can achieve it.

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.