Home Tutorial Poll in AJAX

Poll in AJAX

by MH RISHAD - 23 Apr 2019

Do you like AJAX so far?

Yes:  O
No:   O

Example Explained - The HTML Page

When a user chooses an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:

function getVote(int) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">


The getVote() function does the following:

  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)

The PHP File

The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":

$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
if ($vote == 1) {
  $no = $no + 1;

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");

<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
<?php echo(100*round($yes/($no+$yes),2)); ?>%
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
<?php echo(100*round($no/($no+$yes),2)); ?>%

The value is sent from the JavaScript, and the following happens:

  1. Get the content of the "poll_result.txt" file
  2. Put the content of the file in variables and add one to the selected variable
  3. Write the result to the "poll_result.txt" file
  4. Output a graphical representation of the poll result



Leave a Comment

Required fields are marked *

Stay Connected


Get all latest content delivered to your email free.