ajaxserverupdown

by Tom Scott

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

jQuery(function($) {

    // Hook up our vote handlers
    $("a.vote").live('click', voteClick);

    function voteClick(event) {
        var voteLink, voteType, item, itemId;

        // Regardless of the below, we handle the event, so "consume" it
        event.stopPropagation();
        event.preventDefault();

        // Get the anchor element, wrapped in a jQuery instance
        voteLink = $(this);

        // See if the vote has already been done or is in progress
        if (voteLink.hasClass('done') || voteLink.hasClass('inprogress')) {
            // Ignore the click, possibly tell the user why
            return;
        }

        // Get the vote type
        voteType = voteLink.hasClass('up') ? 'up' : 'down';

        // Get the item we're voting on
        item     = voteLink.closest('.article');

        // Get its ID
        itemId   = item.attr('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.addClass('inprogress');
        $.ajax({
            url:     'savevote',
            data:    {itemId: itemId, voteType: voteType},
            type:    'POST',
            success: votePostSuccess,
            error:   votePostError
        });

        // Called when the POST is successful
        function votePostSuccess(response) {
            // The POST worked
            voteLink.removeClass('inprogress');

            // Did things work on the server?
            if (response === "ok") { // Or whatever
                // Yes, the vote was successfully recorded
                voteLink.addClass('done');
            }
            else {
                // Report an error to the user, the server couldn't record the vote
            }
        }

        // Called when the POST fails for some reason (HTTP errors)
        function...