AJAX Polls
In the following example, we will demonstrate a voting program through which the poll results are displayed without refreshing the page.
Example explanation-HTML page
When the user selects an option above, a function named "Getvote ()" is executed. This function is triggered by an "onclick" event:
- <script>
functionGetvote(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>
<body>
<div Id="Poll">
Do I like PHP and AJAX so far? <form>
Yes:
<input Type="Radio" Name="Vote" Value="0" OnClick="Getvote(This.Value)">
<br>No:
<input type= "Radio " name=" vote " value= "1" onclick = "getvote (thisvalue) >
</FORM>
</DIV>
</BODY>
</HTML>
Copy
The Getvote () function performs the following steps:
- Create a XMLHttpRequest Object
- Create a function that executes when the server responds ready
- Send a request to a file on the server
- Note the parameter (q) added to the end of the URL (contains the contents of the drop-down list)
PHP file
The above server page that is called by JavaScript is a php file named "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);
?>
Result: <table>
<tr>
<td>Yes:</td>
<td>
Width= '<?PHP Echo(100*Round($yes/($no+$yes),2)); ?>‘
Height= ' >
<?PHP Echo(100*Round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
Width= '<?PHP Echo(100*Round($no/($no+ $yes 2?> '
height= ';
<? php echo (100*round< Span class= "pun" > ( $no /( $no + $yes 2 ?>%
</td
</TR>
</table>
Copy
When the selected value is sent from JavaScript to a PHP file, it occurs:
- Get the contents of the "Poll_result.txt" file
- Put the contents of the file into a variable and add 1 to the selected variable
- Write the results to the "poll_result.txt" file
- Output a graphical poll result
Text file
The data from the voting program is stored in a text file (Poll_result.txt).
The data it stores is as follows:
- 3| | 4
Copy
The first number indicates the number of votes for "Yes", and the second number indicates the number of votes for "No".
Note: Please remember to only allow your Web server to edit the text file. Do not let other people gain access, except Web server (PHP).
PHP Instance-AJAX poll