Online Voting System With PHP And AJAX

Github avatar
October 20, 2012. 2 min read

From last few days almost every day there is some news about Obama and Romney. Its been very interesting topic around the world that who will be the next president of USA. I thought this would be a great idea of creating an Online Voting System for next election(just for fun). Before you going to read the post check out the demo and vote you like. Online Voting System With PHP And



Create following files.  —index.html —vote.php index.html

<div id="vote">
<h3>Select Your President!</h3>
<input type="radio" name="vote" value="o" onclick="doVote(this.value)" />Obama
<br />
<input type="radio" name="vote" value="r" onclick="doVote(this.value)" />Romney

This is a simple form with two radio buttons you can choose one. OnClick event will call the javascript function doVote(). dovote()

function doVote(v){
var xhr;
if (window.XMLHttpRequest){
xhr=new XMLHttpRequest();
alert("Your Browser does not support ajax Please upgrade it!");
document.getElementById("vote").innerHTML="<img src='img/loading.gif' />";
if (xhr.readyState==4 && xhr.status==200){

In this function first we will create XMLHttpRequest Object.  Show loading image until we get response. When the response we will display the result. vote.php

$v = $_GET['v'];
//Here our db will be txt file.
$db = "result.txt";
//reads file conts to array
$content = file($db);
$arr = explode(":"undefined $content[0]);
//obama and Romney counts
$o = $arr[0];
$r = $arr[1];
//new values updation
if ($v== o){
$o = $o + 1;
$r = $r + 1;
//updateing new values to file
$update = $o.":".$r;
$fp = fopen($dbundefined"w");
<p class="result" style="width:<?php echo(100*round($o/($r+$o)undefined2)); ?>%">
<?php echo(100*round($o/($r+$o)undefined2)); ?>%
<br />
<span>Romney:<span><p class="result" style="width:<?php echo(100*round($r/($r+$o)undefined2)); ?>%">
<?php echo(100*round($r/($r+$o)undefined2)); ?>%

In this script we will capture the vote value. Update the new values to a file and send back the result in html format. All the votes values will be stored in result.txt. That’s it! Hope you like it. Please comment my work.