PHP

PHP AJAX : Contoh Polling PHP AJAX

AJAX Poll

Contoh berikut akan menunjukkan polling di mana hasilnya ditampilkan tanpa memuat ulang.

Setelah memilih salah satu dari polling di atas, maka akan tampil hasil polling seperti di bawah ini :

Penjelasan Contoh – Halaman HTML

Saat pengguna memilih opsi di atas, fungsi yang disebut “getVote()” dijalankan. Fungsi ini dipicu oleh peristiwa “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" >

Fungsi getVote() melakukan hal berikut:

  • Buat objek XMLHttpRequest
  • Buat fungsi untuk dijalankan saat respons server siap
  • Kirim permintaan ke file di server
  • Perhatikan bahwa parameter (suara) ditambahkan ke URL (dengan nilai opsi ya atau tidak)

File PHP

Halaman di server yang dipanggil oleh JavaScript di atas adalah file PHP yang disebut “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>

Nilai dikirim dari JavaScript dan hal berikut terjadi:

  1. Dapatkan konten dari file “poll_result.txt”
  2. Letakkan konten file dalam variabel dan tambahkan satu ke variabel yang dipilih
  3. Tulis hasilnya ke file “poll_result.txt”
  4. Keluarkan representasi grafis dari hasil polling

File Teks

File teks (poll_result.txt) adalah tempat kami menyimpan data dari polling.

Disimpan seperti ini:

0||0

Angka pertama mewakili suara “Yes”, angka kedua mewakili suara “No”.

Catatan: Ingatlah untuk mengizinkan server web kita mengedit file teks. JANGAN memberikan akses semua orang, hanya server web (PHP).


Hanifah Nurbaeti