PHP 例 - AJAX Poll

❮ 前章へ 次章へ ❯

AJAX Poll

次の例では、結果をリロードせずに表示するpoll(投票)を示します。

ここまでのところ、PHPやAJAXが好きですか?

Yes:
No:

例の説明 - HTMLページ

ユーザが上のオプションを選択すると、"getVote()" という関数が実行されます。 この関数は "onclick"イベントによってトリガされます:

<html>
<head>
<script>
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) {
      document.getElementById("poll").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","poll_vote.php?vote="+int,true);
  xmlhttp.send();
}
</script>
</head>
<body>

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

</body>
</html>

getVote()関数は次の処理を行います:


PHPファイル

上のJavaScriptによって呼び出されるサーバ上のページは、"poll_vote.php"というPHPファイルです:

<?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");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

値はJavaScriptから送信され、次のことを行います:

  1. "poll_result.txt"ファイルの内容を取得する
  2. ファイルの内容を変数に入れ、選択した変数にファイルの内容を追加する
  3. 結果を "poll_result.txt"ファイルに書き出す
  4. poll の結果のグラフ表示を出力する

テキストファイル

テキストファイル (poll_result.txt) は、poll のデータを格納する場所です。

これは次のように格納されます:

最初の数字は "Yes"の票を表し、2番目の数字は "No" の票を表します。

注: Webサーバに、テキストファイルの編集をできるようにすることを忘れないでください。 誰もがWebサーバ(PHP)にアクセスするのを許容しないでください。


❮ 前章へ 次章へ ❯