Search code examples
phpmysqlforumvoting

How is upvote functionality done while staying on the same page? (PHP/MySQL)


I have a relational database and a thread/comment system. I'm having trouble thinking of a way of tackling upvoting, as the page would have to be refreshed for the server to notice any changes.

I've created a new table, UPVOTESTHREAD which consists of two foreign keys, user ID and thread ID, and a primary key which is the combination of the two. The only way I could actually insert into this though is if I submit some POST data. I'm afraid that this would feel clunky to the user, and it would also mean that the user would have to scroooollll down back to where they were just looking at. This can't be the correct solution, right? Is there a better way of doing this?


Solution

  • Yes there is a better solution. It's called AJAX. It sends a post or get request to the server and receives the ouput without reloading the page.

    The script on the server that receives the ajax request can (in your case) increment a vote counter in the db.

    The (usually PHP-) script can also output something (usually json or a status code) that the success handler of the ajax function will receive. You can then modify your page with javascript accordingly. In your case you could receive the current vote count and update the count next to the upvote button if there is a count.