User Poll Script using Ajax and PHP

, , Leave a comment

User Poll Script using Ajax and PHP

In this tutorial, we’ll be creating an Ajax Poll Script that displays the results with colored images using PHP and Ajax.

This is a very simple Ajax poll script. Poll results will be displayed on the current page without moving to another page. The result of the poll is stored in a separate text file and results will be displayed based on the values stored in this file.As the data is saved in flat file it  does not require any database

Download

index.php

<html>
<head>
<script>
function Vote(int)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6 and IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("poll").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>
Do you like PHP Dev Zone?</h3>
<form>
Yes:
<input name="vote" onclick="Vote(this.value)" type="radio" value="1" />

No:
<input name="vote" onclick="Vote(this.value)" type="radio" value="0" />
</form>
</div>
</body>
</html>

vote.php

Result:

<table>
<tbody>
<tr>
<td>Yes:</td>
<td><img alt="poll" height="20" src="pollyes.jpg" width="<?php echo(100*round($yes/($no+$yes),2)); ?>" />
%
</td>
</tr>
<tr>
<td>No:</td>
<td><img alt="poll" height="20" src="pollno.jpg" width="<?php echo(100*round($no/($no+$yes),2)); ?>" />
%
</td>
</tr>
<tr><td></td></tr>
<tr>
<td><a href="http://php-dev-zone.com/2013/05/user-poll-script-using-ajax-and-php.html">Back To Tutorial</a></td></tr>
</tbody>
</table>

Below are the snapshots of the script output.

User Poll Script using Ajax and PHP
User Poll Script using Ajax and PHP