Skip to content

Instantly share code, notes, and snippets.

@Siot Siot/collector.php
Last active Aug 29, 2015

What would you like to do?
Very simple poll with jQuery, PHP and PDO
$host="localhost"; //url of database server;
$dbname=""; //database name;
$user=""; //database username;
$pass=""; //database password;
$table=""; //database table;
//Connection to mysql server;
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
# STH means "Statement Handle"
$data = array('url' => $_REQUEST['url'], 'answer'=> (int) $_REQUEST['answer']);
$STH = $DBH->prepare("INSERT INTO Q_funciona ( url, answer ) values ( :url, :answer)");
$data = array('url' => $_REQUEST['url']);
$STH = $DBH->prepare("SELECT url, answer, COUNT(answer) AS total FROM Q_funciona WHERE url=:url GROUP BY answer");
while($row = $STH->fetch()) {
$array[$row['answer']] = $row['total'];
echo json_encode($array);
# close the connection
$DBH = null;
<!DOCTYPE html>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="survey.js"></script>
<div id="survey">
Are you ok?
<button value="1">Yes</button>
<button value="0">No</button>
//requires jQuery
var origin = window.location.protocol + "//" + + window.location.pathname;
var url = "collector.php"; //url of collector.php;
$(document).ready(function() {
$("#survey button").on("click", function( event ) {
answer = $( this ).val();
xhr_get({url:origin, answer: answer}).done(function(){
$("#survey button").prop("disabled", true)
function is_undefined(data){
if(typeof data === "undefined"){
return "0";
return data;
function xhr_get(data){
return $.ajax({
type: "POST",
dataType: "json",
url: url,
data: data
if(resp !== null){
$("#survey button[value=1]").text("Sí ("+is_undefined(resp[1])+")");
$("#survey button[value=0]").text("No ("+is_undefined(resp[0])+")");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.