DEV Community

Cover image for Building a Real-Time Anonymous Polling System with QuickBlox and Flask
Abhiraj Adhikary
Abhiraj Adhikary

Posted on

Building a Real-Time Anonymous Polling System with QuickBlox and Flask

Introduction

In today's digital world, real-time communication is essential for many applications. Whether you're building chat apps, live voting platforms, or anonymous feedback systems, real-time interaction makes user experiences more engaging. In this post, we’ll dive into building a simple yet innovative real-time anonymous polling system using QuickBlox for communication and Flask for the backend.

The primary goal of this project is to create a polling app where users can vote anonymously in real-time, with the results displayed instantly to all participants in a chat-like interface. Here’s how you can create it from scratch.

Technologies Used

  • QuickBlox: A powerful communication platform providing real-time chat and video features.
  • Flask: A lightweight Python web framework used to manage server-side requests and responses.
  • JavaScript: To handle front-end communication with the server.
  • HTML/CSS: For a sleek, modern UI to display the polling interface.

Features of the Polling System

  1. Anonymous Voting: Users cast votes without revealing their identities.
  2. Real-Time Polling: Results are updated live as each vote is submitted.
  3. Simple Chat-Like Interface: Users can interact with the app in an intuitive environment.

Step-by-Step Guide to Building the Project

1. Setting Up the Backend with Flask

The backend is built using Flask, which handles vote submissions and serves the poll results. Here's a breakdown of the core functionality:

  • Voting API: Accepts votes via POST requests, stores them temporarily, and returns updated poll results.
  • Poll Results API: Provides current poll results to any client upon request.

Here’s how the backend (app.py) works:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

poll_results = {'Option A': 0, 'Option B': 0, 'Option C': 0}

@app.route('/vote', methods=['POST'])
def vote():
    data = request.get_json()
    vote = data.get('vote')
    if vote in poll_results:
        poll_results[vote] += 1
    return jsonify({'results': poll_results})

@app.route('/results', methods=['GET'])
def get_results():
    return jsonify({'results': poll_results})

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

2. Integrating QuickBlox for Real-Time Updates

QuickBlox powers the real-time communication in our app, allowing users to see poll results update live as others vote. Here's how we initialize QuickBlox in the front-end:

// Initialize QuickBlox
QB.init(YOUR_APP_ID, YOUR_AUTH_KEY, YOUR_AUTH_SECRET);

// Function to join chat rooms for voting updates
function joinChat(roomId) {
    QB.chat.join(roomId, { id: roomId }, (err, result) => {
        if (err) {
            console.error('Error joining chat:', err);
        } else {
            console.log('Successfully joined chat room:', result);
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

3. Building the Front-End

The user interface is built using HTML, CSS, and JavaScript. It allows users to cast votes by selecting options from a dropdown menu or typing in a vote.

<div id="chatRoom">
    <h2>Anonymous Polling System</h2>
    <div id="chat"></div>
    <div id="pollResults"></div>
    <input type="text" id="voteInput" placeholder="Enter your vote (Option A, B, C)">
    <button id="voteButton">Vote</button>
</div>
Enter fullscreen mode Exit fullscreen mode

4. Handling User Votes and Displaying Real-Time Poll Results

When users cast a vote, the app sends their vote to the server, updates the results, and then displays them in real-time to all participants in the chat room.

document.getElementById('voteButton').addEventListener('click', async () => {
    const userVote = document.getElementById('voteInput').value.trim();
    if (userVote) {
        await handleVote(userVote);
        document.getElementById('voteInput').value = ''; // Clear the input field
    } else {
        alert('Please enter a valid vote.');
    }
});
Enter fullscreen mode Exit fullscreen mode

5. Real-Time Poll Results

The results of the poll are displayed and updated in real-time as users submit votes. Here’s how the poll results are updated in the chat interface:

export const updateResultsInUI = (results) => {
    const resultsDiv = document.getElementById('pollResults');
    resultsDiv.innerHTML = ''; // Clear previous results

    for (const [option, count] of Object.entries(results)) {
        const resultItem = document.createElement('div');
        resultItem.textContent = `${option}: ${count}`;
        resultsDiv.appendChild(resultItem);
    }
};
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

This project provides a powerful foundation for a real-time polling system. By leveraging QuickBlox for live updates and Flask for backend management, you can expand this concept into more complex voting systems, chat rooms, or interactive event apps.

Try It Out

You can find the full project repository on GitHub: QuickBlox Real-Time Polling App.

Whether you want to improve the UI further, add user authentication, or expand voting options, this project offers plenty of room for growth. Give it a try, and let us know how you use this setup in your own applications!


Top comments (0)