Out of these three options, which method would be most effective for setting up a voting system?

I am in the process of setting up a voting mechanism on my website. I have brainstormed three different methods for implementation and would appreciate your input.

The goal is to allow users to vote on various types of user-generated content related to gaming in a micro Q&A format similar to sites like Stack Overflow, but on a smaller and more specialized scale.

After exploring the following methods, I am struggling to determine which one is most effective.

Method 1: Involves using URL parameters and forms.

Method 2: Involves utilizing URL parameters and jQuery.

Method 3: Utilizes either of the above methods but retrieves information from the database.

The schema assumes that both questions (Q's) and answers (A's) are considered as post objects with distinct postTypeIds, along with the following two tables:

voteTypes(id, voteTypeId, voteName)
votes(id, postId, parentId, userId, ownerUserId, voteTypeId)
  1. The parentId field represents the id of the parent post. It ensures that a question post (postTypeId=1) can only have one accepted answer if the post being voted on is an answer post.
  2. The ownerUserId field corresponds to the userId of the post's owner who is being voted on. This comparison prevents a user from voting on their own posts by verifying it against the session's userId.
  3. The userId field originates from the session and signifies the voter's identity.

Method 1: Create a voting form within the view while iterating over each post in a query. Use hidden fields to capture necessary data.

<input type="hidden" value="@voteTypeId" etc... 

The postId, parentId, and ownerUserId will be extracted from the query output in the view, whereas the userId will derive from the session.

Disadvantages: 1. Users may manipulate data and accept answers to questions they did not ask due to ownerUserId being defined at the view level. 2. Cumbersome: Multiple forms need to be created corresponding to the number of posts displayed in the view. Each post entails four forms, leading to a potentially large number of forms on a single page.

Advantages: 1. Simplicity.


Method 2: Implement anchor tags with custom data attributes alongside jQuery to construct the vote URL.

<a data-vote-type-id="@voteTypeId" data-post-id="@postId" etc...

The ownerUserId, postId, parentId, and voteTypeId will be derived through the URL, while the userId will be fetched from the session.

Advantages: 1. Lightweight design without the necessity for numerous forms. A single jQuery call facilitates submission of any vote via AJAX.

Disadvantages: 1. Disabling JavaScript results in inability to cast votes. 2. Vulnerability to data manipulation since data is transmitted via the URL.


Method 3: Submit solely the voteTypeId and postId via the URL, employing either Method 1 or Method 2. Utilize the postId to interrogate the database, ensuring existence of the post object under consideration as well as validating its ownerUserId and parentId.

If the post exists as an object, establish a newVote entity.

The userId arises from the session, while postId and voteTypeId originate from the URL. The parentId and ownerUserId stem from the retrieved post object.

Advantages: 1. Data integrity maintained to prevent unauthorized modifications by confirming existence of the post object along with its associated details.

Disadvantages: 1. Labour-intensive approach necessitating database queries for retrieving information already available at the view level seems redundant. 2. Denormalized data representation in certain scenarios calls for additional database interactions after successful vote submissions to update relevant tables based on object callbacks, despite the details being accessible at view and controller stages.


Unaddressed aspects: 1. Identifying existing votes to toggle them, requiring further queries. 2. Complicated validation combinations.

I welcome any feedback or alternative suggestions. Thank you!

Answer â„–1

If I were to choose a method, it would be Method 2 with some modifications.

On the server side

Ensure that there are hooks for voting and changing votes that return either true or false depending on whether the operation is successful. Make sure to include parameters such as PostID, VoteTypeID, and UserID. If you encounter any limitations, consider revising your database model (if necessary, opt for a NoSQL approach if a relational database won't suffice).

Do not skip validation; neglecting this step will result in severe consequences. Always perform server-side validation.
Always.

On the client side

The client should receive information from the view and make specific requests to the server. We assume the user is non-malicious; otherwise, they will face obstacles at the backend.

Upon casting or toggling, follow these steps:

  1. Verify if the action is feasible based on the available data in the view
  2. Update the UI to reflect the change
  3. Send the request to the server
  4. If the request returns false, revert the action and display an error message

Advantages of this strategy:

  1. Enhanced security—preventing unauthorized actions through HTTP requests
  2. Users receive prompt responses and clear feedback on errors
  3. Reduced need for extensive error checking due to low occurrence of errors among non-malicious users
  4. For malicious users, any failures at the UI level are their responsibility; the backend remains secure

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

Replacing the absence of value with an empty string within a textfield using Lit-element

In my current project, I am utilizing Lit-element and mwc-element. Within this setup, I have two string variables and an object variable that holds the string values. My goal is to populate a text-field with these object values. So far, I have managed to a ...

Tips for adjusting the <object> video to perfectly match the width and height of its parent container

<div id="player" width='2000px' height='600px'> <object id="pl" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"> <param name='url' value='Video/3.mp4'/> <param name='ShowContro ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

Retrieving text content from a file using React

I've been experiencing difficulties with my fetch function and its usage. Although I can retrieve data from the data state, it is returning a full string instead of an array that I can map. After spending a few hours tinkering with it, I just can&apos ...

Extract each line of text from the ul li tags at every level of the hierarchy with the help of

I am looking to extract a list of strings from the ul and li elements with slash (/) separating each level up to the nth level using JavaScript. I attempted to use both the Jquery.map and each functions, but unfortunately, I was unsuccessful. ...

What is the best way to practice solving linked list problems from LeetCode on your personal computer?

Is there a way to execute the linked list programs on my local machine? I am able to run this code in their input field, but I'm having trouble running it on my local machine. function ListNode(val, next) { this.val = (val===undefined ? 0 : va ...

What is causing the incorrect depth or height in the output of extrudeGeometry?

I am attempting to convert my 2D shape into a 3D shape using extrudeGeometry, but the resulting height is not as expected. The mesh seems to have an unusually high z-depth. Below is the code snippet I am using: const geoPoints = []; geoPoints.push(new THR ...

What is the best way to make a recursive function display every return value in Javascript?

I need help with a function I have been working on. function main() { //retrieve the start text var start_text = document.getElementById("start_text").value; //retrieve target text var target_text = document.getElementById("target_text"). ...

Creating images with LibCanvas

Currently, I am utilizing LibCanvas for canvas drawing on my HTML page. However, I am facing difficulty in drawing an image. Can someone provide assistance with this? UPDATE: The code snippet I am using is showing the image being drawn but then it disappe ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Is it possible to create a horizontal bar graph featuring two different category axes?

I am a beginner with chart.js and I am attempting to create a horizontal bar chart with categories on both the x and y axes. While the axes are displaying correctly, I am unable to see any data on the chart. To troubleshoot, I switched to a line chart and ...

Issue: Unable to 'locate' or 'access' ./lib/React folder while utilizing webpack

I've been delving into the world of React for a while now and decided to experiment with integrating it with webpack. Below is my webpack.config.js : var path = require('path'); module.exports = { entry: './app.js', outp ...

`How to easily download multiple images with just one click``

I am looking for a way to enable users to download multiple images by simply checking the boxes next to each image and clicking a single button. Currently, I have individual download links below each image. I have added checkboxes next to each image for s ...

one webpage featuring HTML-based charts - visual data representation in HTML

I am looking to create HTML charts using a single file that includes JavaScript and jQuery. Specifically, I need the ability to generate line charts, pie charts, and other types of graphs, all within one file. I do not have much knowledge about JavaScript ...

Error message stating that the callback function was not triggered by the injected JSONP script in Angular

Currently, I am running an application on localhost://3000 using npm server. Here is the content of my services file: import {Injectable} from "@angular/core"; import {Jsonp} from "@angular/http"; import 'rxjs/add/operator/map'; @Injectable() ...

Using AJAX to Post Data with Relative Path in ASP.NET MVC 5

I have been developing an MVC 5 web application that utilizes AJAX Posts to invoke Controller Actions. For example, I have a controller named "Account" with an action called "Create". In my Account/Index view, which is rendered by accessing an Account/Ind ...