In this post you will learn how to build a voting system with jQuery, Ajax, PHP and MySQL. Votes will be update at real time and store to the database table with out refreshing or redirecting page. This post is inspired by Reddit and Stack Overflow voting system. This system will allow users to vote up or vote down every single post at once in a session.
Live Demo Download Source
Database Design
At first we need to create a database table called voting. Actually this table stores all information like post contents and voting information.
CREATE TABLE IF NOT EXISTS `voting` ( `id` int(5) NOT NULL AUTO_INCREMENT, `first_name` varchar(45) NOT NULL, `last_name` varchar(45) NOT NULL, `film_info` text NOT NULL, `vote` int(8) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) );
Database Configurations and Connection
This configuration file is responsible for making DB connection. You need to do little bit modify it.
# db configurations define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'root'); define('DB_NAME', 'mydb'); # db connect function dbConnect($close=true){ global $link; if (!$close) { mysql_close($link); return true; } $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error(); if (!mysql_select_db(DB_NAME, $link)) return false; }
PHP & HTML (Retrieve DB Recodes)
<?php include('config.php'); # connect mysql db dbConnect(); $query = mysql_query( 'SELECT id, first_name, last_name, film_info, vote FROM voting LIMIT 0 , 15'); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>jQUery Voting System</title> </head> <body> <div class="wrap"> <?php while($row = mysql_fetch_array($query)): ?> <div class="item" data-postid="<?php echo $row['id'] ?>" data-score="<?php echo $row['vote'] ?>"> <div class="vote-span"><!-- voting--> <div class="vote" data-action="up" title="Vote up"> <i class="icon-chevron-up"></i> </div><!--vote up--> <div class="vote-score"><?php echo $row['vote'] ?></div> <div class="vote" data-action="down" title="Vote down"> <i class="icon-chevron-down"></i> </div><!--vote down--> </div> <div class="post"><!-- post data --> <h2><?php echo $row['first_name'].' '.$row['last_name']?></h2> <p><?php echo $row['film_info'] ?></p> </div> </div><!--item--> <?php endwhile?> </div> <?php dbConnect(false); ?> </body> </html>
Styling
We need to do some styling for post contents and vote buttons. In here, I used Font Awesome for style up vote up and down buttons. If you want you can use image background as you like.
/* voting style */ .vote-span{ width: 60px; float: left; margin: 5px 0; } .vote, .vote-score{ clear: both; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2); cursor: pointer; text-align: center; color: #333; font-size: 1.8em; font-weight: bold; } .vote-score{cursor: text}
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(document).ready(function(){ // ajax setup $.ajaxSetup({ url: 'ajaxvote.php', type: 'POST', cache: 'false' }); // any voting button (up/down) clicked event $('.vote').click(function(){ var self = $(this); // cache $this var action = self.data('action'); // grab action data up/down var parent = self.parent().parent(); // grab grand parent .item var postid = parent.data('postid'); // grab post id from data-postid var score = parent.data('score'); // grab score form data-score // only works where is no disabled class if (!parent.hasClass('.disabled')) { // vote up action if (action == 'up') { // increase vote score and color to orange parent.find('.vote-score').html(++score).css({'color':'orange'}); // change vote up button color to orange self.css({'color':'orange'}); // send ajax request with post id & action $.ajax({data: {'postid' : postid, 'action' : 'up'}}); } // voting down action else if (action == 'down'){ // decrease vote score and color to red parent.find('.vote-score').html(--score).css({'color':'red'}); // change vote up button color to red self.css({'color':'red'}); // send ajax request $.ajax({data: {'postid' : postid, 'action' : 'down'}}); }; // add disabled class with .item parent.addClass('.disabled'); }; }); }); </script>
ajaxvote.php
include('config.php'); # start new session session_start(); dbConnect(); if ($_SERVER['HTTP_X_REQUESTED_WITH']) { if (isset($_POST['postid']) AND isset($_POST['action'])) { $postId = (int) mysql_real_escape_string($_POST['postid']); # check if already voted, if found voted then return if (isset($_SESSION['vote'][$postId])) return; # connect mysql db # query into db table to know current voting score $query = mysql_query(" SELECT vote from voting WHERE id = '{$postId}' LIMIT 1" ); # increase or dicrease voting score if ($data = mysql_fetch_array($query)) { if ($_POST['action'] === 'up'){ $vote = ++$data['vote']; } else { $vote = --$data['vote']; } # update new voting score mysql_query(" UPDATE voting SET vote = '{$vote}' WHERE id = '{$postId}' "); # set session with post id as true $_SESSION['vote'][$postId] = true; # close db connection } } } dbConnect(false);
Perfect been looking for this for a while :) ACES
ReplyDeleteplease can u send de procedure to install it
DeleteHello,
ReplyDeleteHow to save the vote? I mean i create new item via insert in DB, start from 0 and i test to vote. But, when i refresh the page its back to 0. This test in local only so far.
Thanks
Take a look on the ajaxvote.php file. It describe everything about update votes.
Deletemysql_query("
UPDATE voting
SET vote = '{$vote}'
WHERE id = '{$postId}' ");
Its still back again if the page refresh or reload, any clue? lil bit stuck in here.
DeleteThanks
Doesn't work here either. Votes aren't being updated in database.
DeleteBUT CANT UPDATE !!!!!! AHHHHHHH PLS FIX IT
DeleteENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=201 ;
ReplyDeletehow to set this ? "201" where in table hm..
Ignore this line!
Deleteok but no works for me :/
ReplyDeleteHi Resalat..
ReplyDeletethere is a typo in the download package ->config.php define('DB_HOST', 'locahost'); instead of define('DB_HOST','localhost'); "L" was missing nevertheless i coldnt make it vote either ..values in the database do not change.
cheers
martin
Thanks!
DeleteHi Resalat..
ReplyDeleteme again .. your voting system works now with the "dbConnect(); in ajaxvote.php"
Thanks for debugging
Martin
Hello Resalat,
ReplyDeleteThank you for these wonderful scripts, I'm facing the same issue like, it not updating the record on the database, I have the fixed the missing L and I can see dbConnect(); but still not functioning.. can you please advise.
I found my mistake, it works now.. thank you again Resalat for the wonderful script.
DeleteHow did you fix the problem? :)
Deletefor me it was the matter of correcting variable names for my script, once done properly all was functional.
DeleteHad to add:
ReplyDeletedbConnect();
on Line 9 in ajaxvote.php, otherwise votes didn't stick.
Hi Resalat! is there away we can edit the code to vote only once, i mean once you vote once you cannot vote on other items..or using ip, we can validate if he/she voted already
ReplyDeletethis is not the same. Reddit you can click the upvote button to remove your vote, or downvote to change it from +1 to -1. This code can do none of that, and locks in your vote forever.
ReplyDeleteHello, I just hope someone will read my message ^^'.
ReplyDeleteThis looks awesome, I want to use this for my website. I created the table on my MySQL + uploaded the page on my server. I take a looks on the post structure, I know there are some variables. But where I can add titles and descriptions and this for each post ? And how can I add post ?
I'm a beginner but this is too hard for me. The tutorial doesn't show how to use, sorry but I think it's a little shame for those like me who don't have experience...
Sorry but I just found it, it's a SQL request as I supposed but I didn't know the command until now >__>. Sorry for my previous message.
DeleteHi Resalat,
ReplyDeleteThe sql table is only saving the first vote, but not the rest. Do you know a way to fix that?
Got the same problem here :x
DeleteHello thanks a lot for this good work.
ReplyDeleteI am not so good at Php. My most dificult problem is how to add and image to this voting system, thanks a lot.
Great code. Thanks! I have one suggestion in the query to include all entries and order by descending:
ReplyDelete$query = mysql_query(
'SELECT id, first_name, last_name, film_info, vote
FROM voting
ORDER BY vote DESC');
Hey Blake,
DeleteDo you know how I would be able to order posts in order of their vote? So the highest voted posts is at the top of the list.
Thanks,
Rob
Hi Resalat, thanks for your good work.
ReplyDeleteCould you plese check the ZIP file. I found errors in packed ZIP file with source code.
Problem is that as soon as they log out and log back in or clear their cookies they can vote again. This will work as long as you don't mind people being able to game your system.
ReplyDeleteThe zip file is corrupted
ReplyDeleteFile updated! Thanks for your notification!
Deletedemo & download does not work
ReplyDeleteArrow is not getting visible in IE until mouse over.
ReplyDeleteHave you looked into this ?
DeleteHello! I love the style of this, but how could you let users add more to the list?
ReplyDeleteI'd like to know that too !
DeleteDear Brother This code have done helpful. thanks and Go ahead.
ReplyDeleteI am having issues like every one else where it does not update the vote on the server or as an Ifram from a different server.
ReplyDeleteLine 9 has the DBConnect(); and all connection strings are working but it will not save a vote when a user clicks on the up or down arrow.
i've got this working locally (localhost) but when i upload to my server it stops working (cookie/session) issue ??? Thoughts?
ReplyDeleteAt-last it is working in my web "http://bdshowbiz.com/vote"
ReplyDeleteI just replace 'locahost' by 'localhost' in config.php,
and add dbConnect(); in line 10 on ajaxvote.php
Thank you Resalat Haque
Can this script add the function to load data as you scroll down? I've tried to use this script with jscroll but the voting function didn't work then. I want to speed up the page loading and want to load data from mysql dynamically but to retain the voting function. I'd like to hire someone to do this.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteI get this error... :-( Deprecated function: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead i dbConnect() (line 13 in jquery-voting-system/config.php).
ReplyDeleteAnd I got PHP 5.5..
Hello. I used for my main page and work perfect. But I want also use for another page of my web and there is after scrolling displayed again all content from first page. I have on 2nd page another $sql query but code still take from 1st
ReplyDeleteNotice: Undefined variable: link in C:\xampp\htdocs\jewel\jquery-ajax-comment-system\function.php on line 11
ReplyDeleteWarning: mysql_close() expects parameter 1 to be resource, null given in C:\xampp\htdocs\jewel\jquery-ajax-comment-system\function.php on line 11
please solves this problems love commints
ReplyDeletethe problem everyone is having with votes not sticking is a simple fix. change $_POST to $_REQUEST in ajaxvote.php and vote update sticks in database.
ReplyDeleteWRONG
Deletehướng dẫn sử dụng hàm vlookup
ReplyDeletethủ tục hoàn thuế thu nhập cá nhân
chi phí không được khấu trừ khi tính thuế tndn
chi phí không được khấu trừ khi tính thuế tndn
một số lỗi liên quan đến phần mềm htkk
cách kê khai bổ sung thế gtgt
cách lập bảng cân đối kế toán
cách lập báo cáo kết quả hoạt động kinh doanh
cách tính thuế gtgt theo phương pháp khấu trừ
xử lý hóa đơn sai
cách viết hóa đơn gtgt khi bán hàng
xử lý khi viết sai hóa đơn gtgt
lập tờ khai thuế gtgt mẫu 01
cách kê khai thuế gtgt theo tháng quý
cách tính thuế gtgt theo phương pháp trực tiếp
câu hỏi thường gặp về hóa đơn chứng từ
kê khai thuế tndn tạm tính quý
cách tính thuế gtgtg mới nhất
cách lập tờ khai thuế gtgt trên doanh thu 04
cách lập tờ khai thuế tndn 01b
ghi sổ kế toán theo hình thức nhật ký chung
xử lý khi phát hiện thừa thiếu hàng hóa
cách lập tờ khai thuế tndn 01a
xử lý khi phát hiện thừa thiếu hàng hóa
dich vu ke toan thue dich vu lam bao cao tai chinh tín
ReplyDeletekhóa học kế toán thực hành re
cong ty dich vu ke toan
dich vu ke toan tai bac ninh
dịch vụ kế toán trọn gói giá rẻ
dịch vụ kế toán tại tp.hcm
dịch vụ báo cáo thuế
dịch vụ quyết toán thuế uy
học kế toán tại tphcm
học kế toán tại cầu giấy tín
học kế toán tại long biên
học kế toán tại hà đông re
học kế toán tại thanh xuân
học kế toán tại bắc ninh
học kế toán tại bình dương
học kế toán tại hải phòng
dịch vụ thành lập doanh nghiệp trọn gói
dịch vụ thành lập doanh nghiệp tại bắc ninh
dịch vụ quyết toán thuế tại quận 5
dịch vụ quyết toán thuế tại quận 3
dịch vụ quyết toán thuế tại tphcm
dịch vụ quyết toán thuế tại quận cầu giấy
dịch vụ quyết toán thuế tại quận long biên
dịch vụ quyết toán thuế tại quận hà đông
dịch vụ quyết toán thuế tại quận thanh xuân
Hi, the up and down are not working. Pls help
ReplyDeleteThe zip file is not working,can anyone help me ?
ReplyDeletehello i cant connect it to the database can anyone help me
ReplyDeleteplease can anyone send me the guideline as how to install it. am getting to much errors
ReplyDeleteDapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule
ReplyDeleteand obat vig power capsule
The content is well written with detailed information. Great thanks for the awesome share. buy online votes
ReplyDeleteI have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP Training in chennai | PHP Training Course
PHP Training in chennai | Online PHP Course
do i have to write all this code in a single file eith extension .php?
ReplyDeletegood
ReplyDeleteI can't accept, in light of what I see on TV, that anybody can believe any result after the way these cards have been checked, stacked and modified. After this control, the cards are harmed merchandise. Indeed, even paper and stock card makers would have a troublesome time deciding voter plan. Regardless of the possibility that the individuals who have taken care of the describe so far were supplanted by unprejudiced laymen in the court framework, very little more objectitve reality will be come to with respect to who voted in favor of whom. Like a simple-majority voting system
ReplyDeletethe script is SHIT
ReplyDeleteI have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. I like play game five nights at freddy’s 4, game word cookies game , game hill climb racing 2 , hotmail login, and u? I hope people visit my website.
ReplyDeleteOne can vote after every refresh on same post. it will great if one ip can vote only one time.
ReplyDeleteWith the advent of technology, people have moved ahead in terms of standard of living and day to day life, but we have accompanied many unwanted things as well. One of them is stress! There is no proper definition of stress but those into science define it as unrelated response of human body to external force. Gurgaon Escorts
ReplyDeleteI had a problem with the arrow action but I finally figured it out after looking at your code. Check out my project where I did a voting system inside Laravel. https://github.com/TheRealJAG/Laravel-QnA
ReplyDeleteThe blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
ReplyDeleteanimal jam | five nights at freddy's | hotmail login
ReplyDeleteHi Everyone My Self Urvasi From Gurgaon 24x7 Girls Service Escorts provider We Providing Indian Russian Model Call Girls service There Are desirable
Escorts in Gurgaon
Gurgaon Escorts
Escorts Service in Gurgaon
Gurgaon Escorts Service
Thanks a lot! Awesome tutorial. Work like a charm!!!!
ReplyDelete