Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5991105
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T23:20:22+00:00 2026-05-22T23:20:22+00:00

If you have used Stack Overflow for a while, you surely have used the

  • 0

If you have used Stack Overflow for a while, you surely have used the function of vote up and down of the question and answer. I notice Stack Overflow uses <a> anchor. But I don’t know how to POST the data to server. I think it’s JavaScript associated with this <a>, but I can’t find it. How can I implement it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T23:20:22+00:00Added an answer on May 22, 2026 at 11:20 pm

    Yes, JavaScript is involved. There are two parts: Hooking up a handler for the click events on the voting “buttons”, and sending data to the server.

    Hooking up the events is well-covered elsewhere and I won’t go into it here. (For instance, I cover it in this answer.)

    Sending the data to the server, you can use ajax. On any browser that isn’t completely obsolete, you can use XMLHttpRequest:

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/path/to/server/destination");
    xhr.onreadystatechange = handleStateChange;
    xhr.send("id=" + encodeURIComponent(id) +
             "&user=" + encodeURIComponent(userId) +
             "&vote=up");
    function handleStateChange() {
        if (xhr.readyState === 4) {
            // POST complete
            if (xhr.status === 200) {
                // POST complete and we have response, check it
                if (xhr.responseText !== "ok") { // Or whatever you want it to be
                    // Report problem
                }
            } else {
                // Ajax failed, handle/report problem
            }
        }
    }
    

    On more up-to-date browsers you can use fetch:

    var body = new FormData();
    body.append("id", id);
    body.append("user", userId);
    body.append("vote", "up");
    fetch("/path/to/server/destination", {
        method: "POST",
        body: body
    })
    .then(function(res) {
        if (!res.ok) {
            throw new Error("HTTP error " + res.status);
        }
        return res.text(); // or `res.json()` if you return JSON
    })
    .then(function(data) {
        if (data !== "ok") { // Or whatever
            // Report problem
        }
    })
    .catch(function(error) {
        // Ajax failed, handle/report problem
    });
    

    Just for fun, here’s a complete example:

    HTML:

    <div class="article" data-itemid="427">
    <a href="voteup"   class="vote up"  >Up</a>
    <a href="votedown" class="vote down">Down</a>
    <!-- ...the contents of the item... -->
    </div>
    

    JavaScript:

    document.addEventListener("click", function(event) {
        // Regardless of the below, we handle the event, so "consume" it
        event.stopPropagation();
        event.preventDefault();
    
        // Get the anchor element
        var voteLink = event.target.closest("a.vote");
        if (!voteLink) {
            // Didn't find one, bail
            return;
        }
    
        // See if the vote has already been done or is in progress
        if (voteLink.classList.contains("done") || voteLink.classList.contains("inprogress")) {
            // Ignore the click, possibly tell the user why
            return;
        }
    
        // Get the vote type
        var voteType = voteLink.classList.contains("up") ? "up" : "down";
    
        // Get the item we"re voting on
        var item = voteLink.closest(".article");
    
        // Get its ID
        var itemId = item.getAttribute("data-itemid");
    
        // If we didn"t get an ID...
        if (!itemId) {
            // ...report error
            return;
        }
    
        // Mark "in progress" and initiate the vote; action continues
        // in our callbacks below
        voteLink.classList.add("inprogress");
        var body = new FormData();
        body.append("itemId", itemId);
        body.append("voteType", voteType);
        fetch("savevote", {
            method: "POST",
            body:   body
        })
        .then(function(res) {
            if (!res.ok) {
                throw new Error("HTTP error " + res.status);
            }
            return res.text(); // or `res.json()` if you return JSON
        })
        .then(function(data) {
            if (data === "ok") { // Or whatever
                voteLink.classList.add("done");
            } else {
                // Report an error to the user, the server couldn"t record the vote
            }
        })
        .catch(function(error) {
            // Ajax failed, handle/report problem
        })
        .finally(function() {
            // Not in progress anymore
            voteLink.classList.remove("inprogress");
        });
    });
    

    Some notes:

    • The code above is written in ES5 but you could use ES2015+ features in most modern browsers (or by transpiling with tools like Babel).
    • I’ve put an href on the links (which StackOverflow doesn’t have), so that if JavaScript is disabled, we can fall back to going to a page where we let the user vote using a form submission or something. Also, links with href are treated specially by browsers (tab targets, etc.), so this is useful for accessibility. (To really do that, I’d probably have to put the article ID in the href as well.)
    • I’m storing the ID of the item we’re voting on in a data- attribute.
    • We find the item to vote on by locating the “closest” article to the button that was clicked. The DOM’s closest function starts with the element and examines that element to see if it fits the given CSS selector, then if not looks at its parent, then its parent, etc., until it finds a match. So the vote buttons are associated with the article by containment; the article being voted on contains the voting buttons.
    • If you were rooting the event handler in an element deeper in the page (rather than the document level), you’d probably follow the closest check with a contains check to ensure that the element the handler is attached to contains the element that was found (in case it was found in an ancestor element instead). That would be !voteLink || !this.contains(voteLink) above (instead of just !voteLink).
    • I’m using POST because the call changes server state, so GET is inappropriate
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have been using Unity for quite a while but I have always used
I don't have enough Stack Overflow fu yet to have found a previous answer
Hello good people of Stack Overflow, I have come with yet another question for
I have created a Treeview and used a stack panel to include a checkbox,
I have used IPC in Win32 code a while ago - critical sections, events,
I have downloaded the xml dump of the Stack Over Flow site. While transferring
I have been developing iOS apps for a while but they all deal with
this is my first question, although I've already used so many tips from Stack
I have recently managed to get a stack overflow when destroying a tree by
A question I have been thinking about for a while - would Stackoverflow users

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.