Этот скрипт может быть использован для отображения опроса, собора голосов от пользователей и показа результатов голосования с использованием AJAX, не перезагружая страницу в браузере.

Скрипт генерирует необходимый HTML и JavaScript код для показа опроса на веб-странице и отправки ответа пользователя на сервер с помощью AJAX технологии.

Скрипт может также отображать результаты опроса в виде графических полос, которые показывают процентную долю каждого из ответов опроса.

Скрипт позволяет избежать подсчета голосов от одного пользователя на основе IP-адреса пользователя и переменной сессии. Он также использует текстовые файлы на сервере для хранения и обновления результатов опроса.

Лицензия GPL.

Системные требования скрипта:

PHP не младше 5.0 версии.

Исходник скрипта


error_reporting(E_ALL);

class WebExpPoll {
	// poll question
	public $q;

	// Ajax callback (itґs  the name of Ajax function)
	public $f = 'Vote';


	// quiz options
	public $opt;
	// quiz name on radios and ajax div name
	public $quiz = 'vote';

	// page to output poll results
	public $output = 'results.php';

	//images location folder
	public $imgRoot = 'images/';

	// js location folder
	public $jsLocation = '';

	// js file
	public $jsFile = 'poll.js';

	// file where votes are saved
	public $poll_db = 'pool_results.txt';

	// graph images background
	public $graph_bg = 1; // 1 - to random bg   0 - to static bg

	// the image graph  height
	public  $graph_height = '5';

	// message if user cast poll twice
	public $voteRep = "   You already cast this poll !";

	// message result
	public $msgRes  = "<h2>Poll results:</h2>";

	//allow to show table again
	public $showT = 'Show poll';

	// the bg color to options table
	public $TableOptColor = '#ccc';

	// style fonts at options table
	public $TableOptStyle = 'mycssClass';


	public  function __construct($quest ='' , $options = array()) {
		$this->q = $quest;
		$this->opt  = $options;

		WebExpPoll::mountQuiz();
		WebExpPoll::AjaxBuilder();
		WebExpPoll::buildPoolResults();

	}

	protected  function setQuestion() {
		return  $this->q;
	}

	protected  function mountQuiz() {

		$this->form   = '<div id="'.$this->quiz.'">';
		$this->form  .=  ''.$this->setQuestion().'';
		$this->form  .= '<form>';
		$this->form  .= '<table bgcolor=\"'.$this->TableOptColor.'\" border="1">';
		(isset($this->TableOptStyle)) ? ($style = 'class=\"'.$this->TableOptStyle.'\"'): ($style = '');
		foreach($this->opt as $key => $idx){
			$this->form  .= '<tr>';
			$this->form  .= '<td '.$style.'>';
			$this->form  .= $idx;
			$this->form  .= '</td>';
			$this->form  .= '<td>';
			$this->form  .= '<input type="radio" name="'.$this->quiz.'" value="'.$key.'" onclick="'.$this->f.'(this.value)">';
			$this->form  .= '</td>';
			$this->form  .= '</tr>';
		}


		$this->form  .= '</table>';
		$this->form  .= '</form>';
		$this->form  .= '</div>';
		print  $this->form;

	}


	private function AjaxBuilder() {

		$Ajax = 'var xmlHttp

		function Vote(int)
		{
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null)
		 {
		 alert ("Browser does not support HTTP Request")
		 return
		 }
		var url="'.$this->output.'"
		url=url+"?vote="+int
		url=url+"&sid="+Math.random()
		xmlHttp.onreadystatechange=stateChanged
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
		}

		function stateChanged()
		{
		 if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
		 {
		 document.getElementById("'.$this->quiz.'").
		 innerHTML=xmlHttp.responseText;
		 }
		}

		function GetXmlHttpObject()
		{
		var objXMLHttp=null
		if (window.XMLHttpRequest)
		 {
		 objXMLHttp=new XMLHttpRequest()
		 }
		else if (window.ActiveXObject)
		 {
		 objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
		 }
		return objXMLHttp
		}';

		$Filepath = $_SERVER['DOCUMENT_ROOT'].$this->jsLocation.$this->jsFile;

		if(!file_exists($Filepath)){

			$fp = fopen($Filepath,"w");

			 fputs($fp,$Ajax);

		  fclose($fp);

		}

	}

	private	function buildPoolResults(){

		$numOpt = sizeof($this->opt);

		$php  = '<?php'."\n\n";
		$php .= '$ip = $_SERVER["REMOTE_ADDR"];'."\n";
		$php .= '// processes  the votation result'."\n";
		$php .= '$vote  = $_REQUEST["vote"];'."\n";

		$php .= 'if(isset($vote)){'."\n";
		/*$php .=  'if(!headers_sent()){'."\n";
		//$php .= 'session_start();'."\n".'}'."\n";
		*/
		$php .= 'session_start();'."\n";
		$php .=  'if ( session_is_registered("vote")) {'."\n";
		$php .=  "echo \"<img src='".$this->imgRoot."halt.png'> ".$this->voteRep."  \";"."\n";
		$php .=  '}else{'."\n";
		$php .=  'session_register("vote"); '."\n";
		$php .= 'for($i=0;$i<'.$numOpt.';$i++){'."\n";
		$php .= '$d1 .="0,";'."\n";
		$php .= '}'."\n";
		$php .= '$d1 =  substr($d1,0,strlen($d1)-1);'."\n";
		$php .= '$filename = "'.$this->poll_db.'";'."\n";
		$php .= 'if(!is_file($filename)){'."\n";
		$php .= '$fp = fopen($filename,"w");'."\n";
		$php .= 'fwrite($fp,$d1);'."\n";
		$php .= 'fclose($fp);'."\n";
		$php .= '}'."\n";
		$php .= '$content = file($filename);'."\n";
		$php .= '//put content in array'."\n";
		$php .= '$array = explode(",", $content[0]);'."\n";
		$php .= 'foreach($array as $i => $x){'."\n";
		$php .= 'if($vote==$i){'."\n";
		$php .= '$array[$i] +=1;'."\n";
		$php .= '}'."\n";
		$php .= '$rs .= $array[$i].",";'."\n";
		$php .= 'if(ereg(",,",$rs)){'."\n";
		$php .= 'break;'."\n";
		$php .= '}'."\n".'}'."\n";
		$php .= '$fp2 = fopen($filename,"w");'."\n";
		$php .= 'fwrite($fp2,$rs);'."\n";
		$php .= 'fclose($fp2);'."\n";
		$php .= '?>'."\n";
		$php .= ''.$this->msgRes.''."\n";
		$php .= '<?php'."\n";
		$php .= 'function max_key($array) {'."\n";
		$php .= 'foreach ($array as $key => $val) {'."\n";
		$php .= 'if ($val == max($array)) return $key;'."\n";
		$php .= '}'."\n".'}'."\n";
		$php .= '$max = max_key($array);'."\n";
		$php .= '$table  = "<table bgcolor=\"#000000\">";'."\n";
		$php .= '$quiz = array("';
		$php .= ''.implode("\",\"",$this->opt).'");'."\n";
		$php .= '$nt = sizeof($quiz);'."\n";
		$php .= 'foreach($quiz as $n => $itens ){'."\n";
		$php .= '$table .= "<tr>";'."\n";
		$php .= '$table .= "<td style=\"color:#ffffff\">".$itens."</td>";'."\n";
		$php .= '$table .= "<td style=\"color:#ffffff\">";'."\n";
		if($this->graph_bg){
			$php .=	'//Dynamic bg'."\n";
			$php .= '$bg = array("'.$this->imgRoot.'poll_black.gif",'."\n";
			$php .= '"'.$this->imgRoot.'poll_red.gif",'."\n";
			$php .= '"'.$this->imgRoot.'poll_purple.gif",'."\n";
			$php .= '"'.$this->imgRoot.'poll_green.gif",'."\n";
			$php .= '"'.$this->imgRoot.'poll_orange.gif",'."\n";
			$php .= '"'.$this->imgRoot.'poll.gif");'."\n";
			$php .= ''."\n";
			$php .= '$table .="<img src=\"".$bg[array_rand($bg)]."\" width=\"".(100*round($array[$n]/($array[$n]+$array[$max]),2))."\" height=\"'.$this->graph_height.'\">";'."\n";
		} else {
			$php .=	'//Static bg'."\n";
			$php .= '($n ==0   ?  $img = "'.$this->imgRoot.'poll_black.gif"       : ($n==1 '."\n";
			$php .= '?  $img = "'.$this->imgRoot.'poll_red.gif"         : ($n==2'."\n";
			$php .= '?  $img = "'.$this->imgRoot.'poll_purple.gif"      : ($n==3'."\n";
			$php .= '?  $img = "'.$this->imgRoot.'poll_green.gif"       : ($img = "'.$this->imgRoot.'poll.gif" )))));'."\n";
			$php .= ''."\n";
			$php .= '$table .="<img src=\"".$img."\" width=\"".(100*round($array[$n]/($array[$n]+$array[$max]),2))."\" height=\"'.$this->graph_height.'\">";'."\n";
		}

		$php .= '$table .=  (100*round($array[$n]/($array[$n]+$array[$max]),2));'."\n";
		$php .= '$table .= "%";'."\n";
		$php .= '$table .= "</td>";'."\n";
		$php .= '$table .= "</tr>";'."\n";
		$php .='}'."\n";
		$php .='}'."\n";
		$php .= '$table .="</table>";'."\n";
		$php .='echo $table;'."\n";
		$php .= '$_SESSION["vote"] = $ip;'."\n";
		$php .= '}'."\n";
		$php .= 'echo "<br><a href=\"#\" onclick=\"window.location.reload();\">'.$this->showT.'</a>";'."\n";
		$php .='?>'."\n";


		$fp = fopen($this->output,"w");
		fputs($fp,$php);
		fclose($fp);

	}

} // end of class

Скачать архивы

Скачать zip-архив со скриптом.
Скачать tar.gz-архив со скриптом.

captcha