PHP Example - AJAX Poll
AJAX Poll
다음의 예는 결과가 재로딩없이 보여지는 설문조사(poll)를 보여줍니다.
Do you like PHP and AJAX so far?
Example Explained - The HTML Page
사용자가 위에서 하나의 옵션을 선택하면, "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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("poll").innerHTML=xmlhttp.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() 함수는 다음의 작업을 수행합니다:
- Create an XMLHttpRequest 객체를 생성
- 서버 응답이 준비 되었을 때 실행될 함수를 생성
- 서버의 파일에 요청을 보내기
- 파라메타(q)가 (yes 또는 no option 값과 함께) URL에 추가 된 것을 주목하시오
The PHP File
위의 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 로부터 값이 보내지며, 다음과 같은 일이 발생한다.:
- "poll_result.txt" 파일의 내용을 가져온다.
- 변수들에 파일의 내용을 넣고, 선택된 변수에 1을 더한다.
- "poll_result.txt" 파일에 결과를 쓴다.
- 설문조사 결과의 그래픽 표현을 출력한다.
The Text File
텍스트 파일(poll_result.txt)이 설문조사의 데이타를 저장하는 곳이다.
다음과 같이 저장된다:
0||0
첫번 째 숫자는 "Yes" 투표를, 두번 째 숫자는 "No" 투표를 나타낸다.
Note: 웹서버가 텍스트 파일을 편집할 수 있도록 해아함을 기억하십시요. 모든 접근이 아닌, 단지 윕서버(PHP)에게만 허용합니다.