Latest web development tutorials

PHP instance AJAX Vote


In the following examples, we will demonstrate a voting procedure through which the voting results are displayed in the case where the page is not refreshed.

Do you like PHP and AJAX do?


Examples explain - HTML page

When the user selects an option above to execute named "getVote ()" function. This function is triggered by the "onclick" event.

poll.html file code is as follows:

<meta charset="utf-8">
function getVote(int) {
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari 执行代码
    xmlhttp=new XMLHttpRequest();
  } else {
    // IE6, IE5 执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)

<div id="poll">
<h3>你喜欢 PHP 和 AJAX 吗?</h3>
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">


getVote () function performs the following steps:

  • Create XMLHttpRequest object
  • Create function when the server is ready to perform the response
  • File on the server to send requests
  • Please note added to the end of the URL parameter (q) (contains the contents of the drop-down list)

PHP File

Above this server page called by the JavaScript is called "poll_vote.php" PHP files:

$vote = htmlspecialchars($_REQUEST['vote']);

// 获取文件中存储的数据
$filename = "poll_result.txt";
$content = file($filename);

// 将数据分割到数组中
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

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

if ($vote == 1)
  $no = $no + 1;

// 插入投票数据
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");

  <span style="display: inline-block; background-color:green;
      width:<?php echo(100*round($yes/($no+$yes),2)); ?>px;
      height:20px;" ></span>
  <?php echo(100*round($yes/($no+$yes),2)); ?>%
  <span style="display: inline-block; background-color:red;
      width:<?php echo(100*round($no/($no+$yes),2)); ?>px;
  <?php echo(100*round($no/($no+$yes),2)); ?>%

When the selected value is sent from JavaScript to PHP file will occur:

  1. Get Content "poll_result.txt" file
  2. The contents of the file into a variable, the variable selected to be incremented by 1
  3. Writes "poll_result.txt" File Results
  4. Graphical output of poll results

Text File

Text File (poll_result.txt) storing data from the voting procedure.

It stores the data as follows:


The first number indicates "Yes" vote count, and the second number represents the "No" vote count.

Note: Remember to only allow your Web server to edit the text file.Do not let other people get access, in addition to Web server (PHP).