1

So I am doing something with my Arduino Uno where when a button is clicked on my webserver the URL appends '?feed' to the end of it (but is still the same current page). This is absolutely necessary for my Arduino sketch because this is when it knows to rotate my servo.

ANYWAYS. However, I want underneath the button to display the date it was clicked. The problem with this is when the button is clicked, it shows the date for a split second and then reloads the page to append to the URL.

HTML & Javascript (sorry if it's sloppy):

<a href="?feed"><button onclick="displayDate()">FEED ME!</button></a>

<script>
function displayDate() {
    document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>
6
  • Seems like you'd have to pass the date as well, or use the HTML5 URI spec to adjust the url in the address bar without navigating or refreshing the page ... Commented Mar 30, 2015 at 22:23
  • When you click on the button, you are sent to a new page (even if it is the same page). So your code won't run Commented Mar 30, 2015 at 22:23
  • 1
    FYI: button can not be inside an a, that’s invalid HTML. Commented Mar 30, 2015 at 22:24
  • @CBroe: You are right. Relevant spec is here: w3.org/TR/html5/text-level-semantics.html#the-a-element "The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)." Commented Mar 30, 2015 at 22:27
  • @MikeLyons: How would I go about passing the date in the function? Commented Mar 30, 2015 at 22:31

1 Answer 1

1

You might want to use AJAX request with combination of history.pushState. Something like this:

window.onload = function() {
  document.getElementsByClassName('feed')[0].onclick = function() {
    document.getElementById("demo").innerHTML = Date();
    var req = new XMLHttpRequest();
    req.open('GET', '?feed', true);
    req.send(null);
    window.history.pushState(null, null, '?feed');
  };
};
<button class="feed">FEED ME!</button>
<p id="demo"></p>

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

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.