`
wangfengmadking
  • 浏览: 5622 次
  • 性别: Icon_minigender_1
  • 来自: 济南
最近访客 更多访客>>
社区版块
存档分类
最新评论

How To Make an AJAX Poll

阅读更多
One annoying thing about many of the "old-fashioned" style polls which most sites still use is that you must reload an entire page just to submit one little vote. This can be time consuming for people on limited bandwidth, or on sites that it would just be plain impractical to reload the content.

First of all this tutorial will not teach the underlying concepts of AJAX, merely show you how to use it specifically. If you are looking to learn how to use AJAX I suggest you read the tutorial "Retrieving database information with AJAX, PHP and MySQL".

Before we start, here's a sneak peak at the final product: Ajax Poll.

To begin with, we'll set up two MySQL tables: results, and ips. Here are the MySQL queries for both:
CREATE TABLE `results` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `option` varchar(255) NOT NULL,
  `count` bigint(20) NOT NULL DEFAULT '0',
  KEY `id` (`id`)
)
CREATE TABLE `ips` (
`ip` VARCHAR( 255 ) NOT NULL ,
`time` INT NOT NULL
)


The first table "results" has three fields, id, option, and count. Id is simple for identification purposes, option is the name of the option in question, and count is the amount of votes that option received. Each option you wish to have in your poll would have its own row in that table. Further down you will find a simple script to administrate your poll.

Next we need a file that will be accessed by AJAX to add a vote, and retrieve the total votes. This will use PHP to query our mysql tables.
<?php

//We'll call this file vote.php

$id = $_GET['id']; //This is the id of the option the user voted for retrieved through GET

mysql_connect("localhost", "mysql_user", "mysql_password"); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db("mysql_db"); //Select your MySQL database by name

$ip = $_SERVER['REMOTE_ADDR']; //The user's IP address
$query = mysql_query("SELECT * FROM ips WHERE ip = '$ip'") or die("n"); //Query to see if there is already a submission from that IP
if( mysql_num_rows($query) ) //If there has been a submission by that IP already...
{
  die("n"); //End the script and print out "n"
}

$query = mysql_query("SELECT * FROM results WHERE id = $id") or die("n"); //Select the row (option) with the same id as the voteID
if( mysql_num_rows($query) == 1 ) //If there is 1 row found with that id...
{
  mysql_query("UPDATE results SET count = count + 1 WHERE id = $id") or die("n"); //Update the row to add 1 to the count field
  mysql_query("INSERT INTO ips (ip, time) VALUES ('$ip', ". time(). ")") or die("n"); //Insert the user's IP into the database so they can't vote again
  $query2 = mysql_query("SELECT * FROM results WHERE id = $id") or die("n"); //Same as original query to get the new value of count
  if( mysql_num_rows($query2) == 1 ) //If there is 1 row found with that id...
  {
    $row = mysql_fetch_assoc($query2); //Use $row as the associative fetching key
    $count = $row['count']; //$count is now the value of the count field for the option's row
  }
  $updated = "y"; //If we got to here, it means that the row has been updated so we set this variable to "y" which will be echoed out to tell our AJAX script whether or not it worked
}
else
{
  $updated = "n"; //Same deal except this would only be gotten to if we did not successfully update so it's set to "n"
}

echo $updated. $count; //Echo out "y" or "n" and the new count

?>

As I'm sure you can gather from the comments this script the goal is to add one vote to the option the user has voted for, then retrieve the new amount of votes for that option. The final result is either going to be "n" or "y#" (# representing the new amount of votes). The only way the output would be "n" would be if the user somehow voted for something that didn't exist, there was a database error, or they previously had voted.

We now have all the server-side coding complete for the updating and retrieving, so now we need to get the AJAX setup so that these can be used. This is the JavaScript that will be on the page that contains the poll.
function vote(id){
var xmlhttp=false; //Clear our fetching variable
        try {
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); //Try the first kind of active x object…
        } catch (e) {
                try {
                        xmlhttp = new
                        ActiveXObject('Microsoft.XMLHTTP'); //Try the second kind of active x object
            } catch (E) {
                xmlhttp = false;
                        }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
        }
        var file = 'vote.php?id='; //This is the path to the file we just finished making
    xmlhttp.open('GET', file + id, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
                var content = xmlhttp.responseText; //The content data which has been retrieved
                if( content != 'n' ){ //If the response was not "n" (meaning it worked)
                      content = content.replace('y', ''); //Get rid of the y infront of our result *
                                          document.getElementById('option' + id).innerHTML = content; //Set the inner HTML of the div with the old value in it to the new value **
                }
        }
        }
        xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}

As you can see it is not very different compared to simple retrieval, because most of what we are doing is server-side. I only have two things I wanted to explain further, marked by the stars by their comments.

*
content = content.replace('y', '');

I just starred this to make sure that everyone could understand what was going on. If we got to this stage in the script, it means that we would get a result that looked like "y#", when all we wanted was the "#". This just replaces the "y" with nothing so that only the number remains.

**
document.getElementById('option' + id).innerHTML = content;

I starred this just because I wanted to create a mental image of what it was. Each value for "votes" will be displayed in its own div, so that when it is voted for we can just replace the inner HTML of that div with the new value.

We now need to originally display this data using PHP. This code will be embedded into the document somewhere. I warn you it's not very pretty to look out (the echoed out result), however it is easy to modify it to fit your own site!
<?php

mysql_connect("localhost", "mysql_user", "mysql_pass"); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db("db_name"); //Select your MySQL database by name

$query = mysql_query("SELECT * FROM results ORDER BY count DESC") or die(mysql_error()); //Query all possible options ordering by total votes
if( mysql_num_rows($query) ) //If there are any results to show...
{
  while( $row = mysql_fetch_array($query) ) //Begin a loop to echo out each option
  {
    echo '<br /><strong>'. $row['option']. ' <a href="javascript:vote('. $row['id']. ')">Vote!</a></strong><div id="option'. $row['id']. '">'. $row['count']. '</div>'; //Echo out each option, vote link, and total votes
  }
}
else
{
  echo "<p>Sorry, there are no options to vote for!</p>"; //Otherwise we echo out that message
}

?>


Now here is a SAMPLE page. You would most likely not want to have your page looking like this as it is quite boring. It is very easy though to take the pieces of code as examples and incorporate them into your own design. I'm just displaying this so that you can see the whole script in action.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Look! A Poll!</title>
<script language="javascript" type="text/javascript">
function vote(id){
var xmlhttp=false; //Clear our fetching variable
        try {
                xmlhttp = new ActiveXObject('Msxml2.XMLHTTP'); //Try the first kind of active x object…
        } catch (e) {
                try {
                        xmlhttp = new
                        ActiveXObject('Microsoft.XMLHTTP'); //Try the second kind of active x object
            } catch (E) {
                xmlhttp = false;
                        }
        }
        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest(); //If we were able to get a working active x object, start an XMLHttpRequest
        }
        var file = 'vote.php?id='; //This is the path to the file we just finished making
    xmlhttp.open('GET', file + id, true); //Open the file through GET, and add the id we want to retrieve as a GET variable
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4) { //Check if it is ready to recieve data
                var content = xmlhttp.responseText; //The content data which has been retrieved
                if( content != 'n' ){ //If the response was not "n" (meaning it worked)
                      content = content.replace('y', ''); //Get rid of the y infront of our result *
                                          document.getElementById('option' + id).innerHTML = content; //Set the inner HTML of the div with the old value in it to the new value **
                }
        }
        }
        xmlhttp.send(null) //Nullify the XMLHttpRequest
return;
}
</script>
</head>
 
<body>
<p>Question? <!-- Replace with your actual question of course! --></p>
<?php

mysql_connect("localhost", "mysql_user", "mysql_pass"); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db("db_name"); //Select your MySQL database by name

$query = mysql_query("SELECT * FROM results ORDER BY count DESC") or die(mysql_error()); //Query all possible options ordering by total votes
if( mysql_num_rows($query) ) //If there are any results to show...
{
  while( $row = mysql_fetch_array($query) ) //Begin a loop to echo out each option
  {
    echo '<br /><strong>'. $row['option']. ' <a href="javascript:vote('. $row['id']. ')">Vote!</a></strong><div id="option'. $row['id']. '">'. $row['count']. '</div>'; //Echo out each option, vote link, and total votes
  }
}
else
{
  echo "<p>Sorry, there are no options to vote for!</p>"; //Otherwise we echo out that message
}

?>
</body>
</html>

And there you have it! You now have all the skill to make your own displayable poll! This next part is optional, and it is just some PHP scripts that show you how you could add and delete options through your own little admin panel.
<?php

//Name this file whatever you want (.php of course ;) )

mysql_connect("localhost", "mysql_user", "mysql_password"); //Connect to the MySQL server with your host (probably localhost), your mysql username, and your mysql password
mysql_select_db("db_name"); //Select your MySQL database by name

$del = intval($_GET['del']); //Retrieve the integer value of del through GET
if( $del ) //If there is actually something in the del variable...
{
  mysql_query("DELETE FROM results WHERE id = '$del'") or die(mysql_error()); //Delete the option with that id
  echo "<p>Thank you, the option you chose to delete was deleted.</p>"; //Echo out that message <--
}

if( $_POST['addOption'] ) //If the form for a new option has been submitted...
{
  $option = addslashes($_POST['addOption']);
  mysql_query("INSERT INTO `results` (`option`) VALUES ('$option')") or die(mysql_error()); //Insert a new row for that option
  echo "<p>Thank you, your option has been added!</p>"; //Echo out that message <--
}

$query = mysql_query("SELECT * FROM results") or die(mysql_error()); //Query all of the options
if( !mysql_num_rows($query) ) //If no rows are found...
{
  echo "<p>There are no options currently in the database.</p>"; //Echo out that there are none to be found
}
else
{
  while( $row = mysql_fetch_array($query) ) //Set up a loop for the query using $row as the fetching variable
  {
    echo "<p>". $row['option']. " - <a href=\"?del=". $row['id']. "\">delete</a></p>"; //Echo out each option with a delete link
  }
}

echo "<form name=\"add\" method=\"post\" action=\"$PHP_SELF\">
<p><input type=\"text\" name=\"addOption\" /><input type=\"submit\" name=\"addSubmit\" value=\"Submit\" /></p>
</form>";

?>

Tips for modification

The main thing you would need to modify for this script would be the display because it is designed for utter simplicity. What you would want to change would be anything that is being displayed through echo. If you have a basic knowledge of HTML you should be able to change the various echoed out strings to fit your layout.
分享到:
评论

相关推荐

    [工具查询]Dracon Ajax Poll 1.1_dracon_poll.zip

    【 Dracon Ajax Poll 1.1 介绍与详解】 Dracon Ajax Poll 是一款基于Ajax技术的投票系统,主要用于网站互动功能的实现。Ajax(Asynchronous JavaScript and XML)是一种在无需刷新整个网页的情况下,能够更新部分...

    基于PHP的-MySQL-Ajax投票控件 Dracon Ajax Poll.zip

    4. Dracon Ajax Poll控件: Dracon Ajax Poll是一个具体的实现,它包含前端的HTML、CSS和JavaScript代码,以及后端的PHP脚本。前端部分负责展示投票界面,接收用户输入,使用Ajax发送投票请求;后端部分则处理投票...

    websocket long poll Ajax使用测试

    客户端访问服务器方式使用,包含Ajax原生,long poll,Websocket 客户端访问服务器方式使用,包含Ajax原生,long poll,Websocket 客户端访问服务器方式使用,包含Ajax原生,long poll,Websocket 客户端访问服务器...

    商业编程-源码-Dracon Ajax Poll v1.1.zip

    在实际应用中,开发者可以依据Dracon Ajax Poll v1.1的源码进行二次开发,定制适合自己业务需求的投票功能。例如,增加身份验证机制以防止刷票,或者添加投票统计图表以直观展示结果。同时,源码的开放性也使得...

    PHP实例开发源码—PHP-MySQL-Ajax投票控件 Dracon Ajax Poll.zip

    6. **前端框架**:Dracon Ajax Poll可能使用某种前端框架(如Bootstrap或自定义CSS/JS)来美化界面和响应式布局,确保在不同设备上都能良好展示。 7. **JSON**:虽然描述中没有明确提及,但Ajax通信通常使用JSON...

    Serial-Programming-HOWTO.pdf

    - **文档名称**:《Serial Programming HOWTO》 - **作者**:Gary Frerking (维护者) 和 Peter Baumann (初版作者) - **版权信息**:本文档版权所有 ©1997 Peter Baumann, ©2001 Gary Frerking,并根据Linux文档...

    PHP-MySQL-Ajax投票控件DraconAjaxPollv1.1

    由于软件生命周期中可能存在bug修复、性能优化和新特性添加,Dracon Ajax Poll的维护工作包括定期检查更新、应用补丁,以及适应不断变化的Web技术和用户需求。 综上所述,Dracon Ajax Poll是一个集成了PHP编程、...

    modbus poll工具+Modbus Poll Key.txt

    Modbus Poll是一款强大的Modbus协议测试工具,常用于工业自动化领域的设备通信调试。它允许用户模拟Modbus主设备,与支持Modbus协议的从设备进行交互,以验证设备的正确功能或诊断通信问题。该工具提供了图形化界面...

    ajax+php实现了投票的功能

    Ajax(Asynchronous JavaScript and XML)是一种在无需刷新整个网页的情况下,能够更新部分网页内容的技术。PHP是一种服务器端脚本语言,常用于处理动态网页内容,如用户提交的数据。 首先,`index.html`是项目的主...

    Modbus_Poll_9.5.rar Modbus Poll

    Modbus Poll is a Modbus primary emulator designed primarily to help Modbus device developers or others wanting to test and emulate the Modbus protocol.

    Modbus Poll v6.3.1.zip

    Modbus Poll是一款实用的modbus开发和调试工具,可以非常方便的进行modbus调试,是一款非常有用的Modbus主机模拟程序。内含32 64位双版本及注册码。 Modbus Poll功能介绍: OLE自动化可以简单地与Visual Basic接口...

    Ajax-jquery-longpoll-client.zip

    Ajax-jquery-longpoll-client.zip,简单的客户端longpoll实现,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小部分在不重新加载网页...

    poll-plugin:Poll 插件将 AJAX Poll 系统添加到您的 OctoberCMS 网站。 您可以轻松地将投票添加到您的网站页面

    Poll 插件为您的网站添加了一个 AJAX Poll 系统。 您可以轻松地将投票添加到您的网站页面 特征 您可以在更新页面查看每次投票的投票结果。 更新页面:[backendurl]/shahiemseymor/poll/polls/update/[pollId] 在...

    Modbus Poll 9.2.2 Build.zip

    Modbus Poll是一款强大的Modbus协议调试工具,专用于物联网(IoT)设备的通信测试与诊断。该软件允许用户通过串行端口(Serial Port)或网络连接与支持Modbus协议的设备进行交互,以便进行数据读取、写入以及设备...

    linux内核poll源码剖析

    Linux 内核 poll 源码剖析 poll 系统调用是 Linux 内核中一个重要的系统调用,它允许用户空间程序监视文件描述符的可读或可写事件。在 Linux 内核中,poll 系统调用是通过 sys_poll 函数来实现的。在本文中,我们将...

    modbus poll 7 序列号 注册码

    在探讨“modbus poll 7 序列号 注册码”的相关知识点时,我们首先要明确几个概念:Modbus Poll 7 软件是什么?序列号与注册码的意义及其应用场景,以及如何正确地使用这些信息。 ### Modbus Poll 7 软件介绍 #### ...

    Ajax-yii2-longpoll.zip

    Ajax-yii2-longpoll.zip,实现长轮询连接,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建动态网页,其中网页的小部分在不重新加载网页的情况下更改。

    Modbus Poll version 10.5.0 Build 1946 self-installing

    《Modbus Poll 10.5.0 Build 1946 自安装程序:深入了解Modbus通讯技术》 Modbus Poll版本10.5.0 Build 1946的自安装程序是一款专为测试和调试Modbus设备而设计的强大工具。这个软件包包括了64位和32位两种体系架构...

    modbuspoll使用说明_modbus_MODBUSPOLL_modbuspoll_

    **Modbus Poll 使用详解** Modbus Poll是一款专为Modbus通信协议设计的高效开发与调试工具,它允许用户模拟Modbus主设备,从而对Modbus从设备进行测试和验证。这款软件广泛应用于工业自动化领域,因为Modbus协议是...

    ModbusPoll-v7.0.0

    ModbusPoll-v7.0.0 是一个专用于测试和诊断Modbus协议设备的软件工具。这个版本提供了永久使用权限,意味着用户可以无限制地利用它来调试和监控基于Modbus通信的硬件设备。在工业自动化领域,Modbus是一种广泛采用的...

Global site tag (gtag.js) - Google Analytics