PHP development...LOGIN

PHP development basic tutorial AJAX voting

AJAX voting

In the following example, we will demonstrate a voting program through which the voting results are displayed without refreshing the web page. show.

The page display is shown in the picture on the right

When the user selects one of the above options, a function named "getVote()" will be executed. This function is triggered by the "onclick" event.

This example includes three parts

  • HTML form

  • PHP file

  • TXT file


HTML file:

See 1.php for the source code

<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
<script>
function getVote(int) {
  //创建 XMLHttpRequest 对象
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari 执行代码
    xmlhttp=new XMLHttpRequest();
  } else {
    // 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","2.php?vote="+int,true);
  xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>你喜欢 PHP 和 AJAX 吗?</h3>
<!-- 用户选择一个选项,触发onclick事件,执行getVote()函数 -->
<form>
是:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>否:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

The above HTML page contains a simple HTML form with two radio buttons in the <div> element.

The form works like this:

  • When the user selects "yes" or "no", an event is triggered

  • When the event is triggered, the getVote() function is executed

  • Surrounding the form is a <div> named "poll". When data is returned from the getVote() function, the returned data replaces the form.

getVote() function will perform the following steps:

  • Create XMLHttpRequest object

  • Created in Function executed when the server response is ready

  • Send a request to a file on the server

  • Please note the parameter (q) added to the end of the URL ( Contains the contents of the drop-down list)


PHP file:

The server called by JavaScript in the above paragraph The page is a PHP file named "2.php":

<?php
//过滤浏览器传过来的数据
$vote = htmlspecialchars($_REQUEST['vote']);

// 获取文件中存储的数据
$filename = "3.txt";
$content = file($filename);

// 将数据分割到数组中
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
{
  $yes = $yes + 1;
}

if ($vote == 1)
{
  $no = $no + 1;
}

// 插入投票数据
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");//写入方式打开
fputs($fp,$insertvote);//将$insertvote写入文件中
fclose($fp);//关闭打开文件
?>

<h2>结果:</h2>
<table>
  <tr>
  <td>是:</td>
  <td>
  <span style="display: inline-block; background-color:green;
      width:<?php echo(100*round($yes/($no+$yes),2)); ?>px;
      height:20px;" ></span>
  <?php echo(100*round($yes/($no+$yes),2)); ?>%
  </td>
  </tr>
  <tr>
  <td>否:</td>
  <td>
  <span style="display: inline-block; background-color:red;
      width:<?php echo(100*round($no/($no+$yes),2)); ?>px;
      height:20px;"></span>
  <?php echo(100*round($no/($no+$yes),2)); ?>%
  </td>
  </tr>
</table>

When the selected value is sent from JavaScript to the PHP file, what happens:

  • Get" poll_result.txt" The contents of the file

  • Put the file contents into the variable and add 1 to the selected variable

  • Write the result" poll_result.txt" file

  • Output graphical voting results


##TXT file

The data from the voting program is stored in a text file (3.txt).

It looks like this:

0||0

The first number represents a "Yes" vote, and the second number represents a "No" vote.

Note: Remember to allow only your web server to edit this text file. Don't let anyone else gain access except the web server (PHP).




##Learning experience This example mainly includes the following knowledge points:

    Form basics: radio button
  • ## onclick event: Occurs when the object is clicked
  • Function call, function value passing

  • Creation of AJAX XMLHttpRequest object, function executed when the server responds, sending request to the file on the server: See 1-5 for learning experience

  • HTML DOM getElementById() method: Returns a reference to the first object with the specified ID

PHP related operations on files:

  • file(): Read the entire file into an array

  • fopen(): Open the file or URL

  • fputs(): Write to file

  • fclose(): Close an open file

Related functions:

  • htmlspecialchars(): Convert predefined characters into HTML entities

  • explode(): Break up the string For array

Next Section
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script> function getVote(int) { //创建 XMLHttpRequest 对象 if (window.XMLHttpRequest) { // IE7+, Firefox, Chrome, Opera, Safari 执行代码 xmlhttp=new XMLHttpRequest(); } else { // 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","2.php?vote="+int,true); xmlhttp.send(); } </script> </head> <body> <div id="poll"> <h3>你喜欢 PHP 和 AJAX 吗?</h3> <!-- 用户选择一个选项,触发onclick事件,执行getVote()函数 --> <form> 是: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"> <br>否: <input type="radio" name="vote" value="1" onclick="getVote(this.value)"> </form> </div> </body> </html>
submitReset Code
ChapterCourseware