Drupalwoo ☉

How to Implement a Simple Voting System in Drupal with JavaScript

Community sites often need a quick preference poll: a Sydney café might ask which weekend event should feature, while a Melbourne arts group might choose its next workshop theme. The interface can feel immediate with JavaScript, but Drupal should remain the authority for every accepted vote. This keeps the public experience lightweight without making browser state the only record.

The example below uses a small custom Drupal module, one content type, and a server endpoint protected by a CSRF token. It supports anonymous and logged-in readers, limits repeat voting, and offers a no-JavaScript form fallback. The patterns suit Drupal 10 and 11 and remain close to the APIs used by maintained Drupal releases.

Approach Where votes live Repeat-vote control Suitable for
Browser-only JavaScript One visitor's browser Easily changed or removed Interface mock-ups
Drupal form with AJAX Drupal and its database Depends on form rules Simple editorial polls
JavaScript with a protected endpoint Drupal and its database Server-side session or account rules Reliable interactive voting

Choose a voting architecture

A browser-only implementation can save choices in localStorage, but each visitor sees a different tally and can edit values through developer tools. That is acceptable for a prototype, not for a community decision or anything reported publicly.

The protected endpoint pattern in the comparison keeps counts in Drupal, validates every choice on the server, and returns the authoritative total. JavaScript improves feedback; it should never determine whether a vote is legitimate.

This matters for Australian audiences in Brisbane, regional New South Wales, and other areas where mobile coverage can fluctuate. A retried request must not create two votes, so the server should resolve repeated submissions from the same voter and poll to one recorded vote.

Model the poll in Drupal

Create a Poll content type with a question, a list-text field for choices, an integer field for the vote count, and an optional closing date. A boolean enabled field is useful when an editor wants to pause a poll without unpublishing it. Start every new count at zero.

One count field on the poll node is simpler than creating a node for each ballot. It also gives editors a familiar place to review results. If a strict audit trail is required, record accepted votes separately with a poll identifier, choice, timestamp, and privacy-safe voter key.

Render the question and radio buttons in a template preprocess or custom paragraph. Pass the poll identifier, current count, generated form action, and a CSRF token created with the drupalwoo_poll value to the template; never calculate totals in JavaScript or accept a count posted by the browser.

Create a secure vote endpoint

Create a drupalwoo_poll module, define cast poll votes in its permissions file, and register the controller and vote service in drupalwoo_poll.services.yml. The controller needs node storage, the CSRF generator, current-user service, cache, lock factory, private-key service, and logger. Then add a POST route and grant the permission to the intended roles.

drupalwoo_poll.vote:
  path: '/api/poll/{node}/vote'
  defaults:
    _controller: '\Drupal\drupalwoo_poll\Controller\PollVoteController::vote'
  requirements:
    _permission: 'cast poll votes'
    node: \d+
  methods: [POST]

The controller loads the poll, confirms that it is published, enabled, and open, then checks that the submitted choice exactly matches a configured option. It must also validate a token before changing anything.

$token = $request->headers->get('X-CSRF-Token')
  ?: $request->request->get('_token');
if (!$this->csrfToken->validate($token, 'drupalwoo_poll')) {
  return new JsonResponse(['message' => 'Invalid token.'], 419);
}

For duplicate prevention, derive a key from the poll identifier plus the logged-in user ID or anonymous session ID, then hash that combination with a private key. Store the marker for a defined period. A lock around the duplicate check, count update, and marker write prevents simultaneous requests from both succeeding. If repeat votes must be impossible even after cache eviction, use a database table with a unique poll-and-voter constraint instead of cache entries.

Connect the form with JavaScript

Render a normal form so it still works when scripting is unavailable. JavaScript intercepts submission, sends JSON, and replaces the page response with an inline status message.

<form class="drupalwoo-poll" method="post" action="{{ vote_url }}">
  <input type="hidden" name="_token" value="{{ csrf_token }}">
  <fieldset>
    <legend>{{ question }}</legend>
    {% for choice in choices %}
    <label>
      <input type="radio" name="choice"
        value="{{ choice|escape('html_attr') }}" required>
      {{ choice }}
    </label>
    {% endfor %}
  </fieldset>
  <button type="submit">Cast vote</button>
  <output data-poll-count aria-live="polite">{{ votes }}</output>
  <p data-poll-status role="status"></p>
</form>

Attach one listener per form. Keep the submit button enabled until the response arrives, but prevent a second click while the request is running.

document.querySelectorAll('.drupalwoo-poll').forEach((form) => {
  const button = form.querySelector('button[type="submit"]');
  const status = form.querySelector('[data-poll-status]');
  const count = form.querySelector('[data-poll-count]');

  form.addEventListener('submit', async (event) => {
    event.preventDefault();
    button.disabled = true;
    status.textContent = 'Recording your vote…';

    try {
      const choice = new FormData(form).get('choice');
      const response = await fetch(form.action, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': form.querySelector('[name="_token"]').value
        },
        body: JSON.stringify({choice})
      });
      const result = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(result.message || 'Vote could not be recorded.');
      }

      count.textContent = result.votes;
      form.querySelectorAll('input').forEach((input) => {
        input.disabled = true;
      });
      status.textContent = 'Your vote has been recorded.';
    } catch (error) {
      status.textContent = error.message;
      button.disabled = false;
    }
  });
});

On success, update the count from the server response and disable the choices. On failure, restore the button and show a concise message. The endpoint can distinguish JSON requests from ordinary form posts, redirecting the latter back to the poll with a flash message.

Handle errors and accessibility

Return meaningful status codes: 400 for an invalid choice, 403 for a closed poll, 409 for an existing vote, 419 for an invalid token, and 429 for rate limiting. Keep client messages safe and plain while logging technical details for administrators. An unexpected server failure should produce a recoverable message rather than an empty panel.

Use a radio group inside a fieldset with a meaningful legend, and retain visible labels so the choice is clear without relying on colour. Keyboard users must reach every control, and focus should move predictably after an error. An aria-live region announces the new count and status; do not repeatedly announce the entire form.

For a broader Drupal perspective, Maxwell’s Drupal resources offer a useful adjacent reference when refining the visual treatment. Keep the voting behaviour independent of those design choices so a theme update cannot alter validation, duplicate protection, or stored results.

Apply Australian privacy practices

Under the Privacy Act 1988 and the Australian Privacy Principles, a poll can involve personal information even when the form does not request a name. A hashed account or session identifier may still be personal information in context, so treat it conservatively, limit retention, and document the purpose. Do not collect raw IP addresses merely to enforce duplicate voting.

Explain which session cookie is needed, how long a vote marker remains, and whether results are public. On a Drupalwoo-based site, make the poll notice easy to find from the privacy policy, then add any site-specific contact or retention details. Provide a deletion process where identifiers are retained.

Avoid email collection unless a stated purpose requires it. If commercial electronic messages will follow, account for the Spam Act 2000, including consent, sender identification, and a functional unsubscribe method. Store timestamps in UTC and convert them to Australia/Sydney for display, where daylight saving changes between AEST and AEDT. Use a clear day-first date format. Australian councils, community organisations, independent magazines, and local clubs can all use this pattern, but each should publish only the data its purpose requires.

Test and operate the feature

Test anonymous and authenticated voting, duplicate requests, invalid choices, closed polls, expired tokens, direct calls to the endpoint, and two submissions arriving together. Repeat the critical path in Chrome, Safari on iOS, and a throttled mobile connection. The staging site should use the same token, session, and cache configuration as production.

Deploy the module as versioned code, import the content type and field configuration through Drupal configuration management, and back up the database before enabling the poll on a busy site. Australian hosting can reduce network distance, but data-residency and privacy commitments still need a separate decision.

Monitor aggregate request failures, rejected votes, and unusual traffic without logging voter identifiers in plain text. Give the cached duplicate marker a realistic expiry, document how to clear it, and revisit the access rule when staff or community roles change. With those controls in place, the finished feature stays responsive for readers while Drupal retains the authoritative count, clear validation, and an auditable configuration.