ตัวอย่าง PHP - AJAX Poll
AJAX โพล
ตัวอย่างต่อไปนี้จะสาธิตโพลที่แสดงผลโดยไม่ต้องโหลดซ้ำ
คุณชอบ PHP และ AJAX จนถึงตอนนี้หรือไม่?
ตัวอย่างที่อธิบาย - หน้า HTML
เมื่อผู้ใช้เลือกตัวเลือกด้านบน ฟังก์ชันที่เรียกว่า "getVote()" จะถูกดำเนินการ ฟังก์ชั่นถูกทริกเกอร์โดยเหตุการณ์ "onclick":
<html>
<head>
<script>
function getVote(int)
{
var xmlhttp=new XMLHttpRequest();
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() ทำสิ่งต่อไปนี้:
- สร้างวัตถุ XMLHttpRequest
- สร้างฟังก์ชันที่จะดำเนินการเมื่อการตอบสนองของเซิร์ฟเวอร์พร้อม
- ส่งคำขอไปยังไฟล์บนเซิร์ฟเวอร์
- สังเกตว่ามีการเพิ่มพารามิเตอร์ (โหวต) ลงใน URL (ด้วยค่าของตัวเลือกใช่หรือไม่ใช่)
ไฟล์ PHP
หน้าบนเซิร์ฟเวอร์ที่เรียกใช้โดย JavaScript ด้านบนเป็นไฟล์ PHP ชื่อ "poll_vote.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"
- ใส่เนื้อหาของไฟล์ในตัวแปรและเพิ่มหนึ่งในตัวแปรที่เลือก
- เขียนผลลัพธ์ลงในไฟล์ "poll_result.txt"
- แสดงผลแบบกราฟิกของผลการสำรวจความคิดเห็น
ไฟล์ข้อความ
ไฟล์ข้อความ (poll_result.txt) คือที่ที่เราจัดเก็บข้อมูลจากการสำรวจความคิดเห็น
มันถูกเก็บไว้เช่นนี้:
0||0
ตัวเลขแรกหมายถึงการโหวต "ใช่" หมายเลขที่สองหมายถึงการโหวต "ไม่ใช่"
หมายเหตุ:อย่าลืมอนุญาตให้เว็บเซิร์ฟเวอร์ของคุณแก้ไขไฟล์ข้อความ อย่า ให้ทุกคนเข้าถึงได้ เฉพาะเว็บเซิร์ฟเวอร์ (PHP)