Saturday 25 January 2014

Creating a simple voting site with Hoist

I needed to create a simple site (2 page) that would let people vote on when my baby would be born.
Not wanting the trouble of hosting the database or creating the api to store the data, I turned to Hoist

With the easy to use javascript library found at https://github.com/hoist/hoist-js I was quickly able to create the voting app I needed. 

Here how:

To Vote:
var rawvote = {}
rawvote.date = $("#date-here").text();
rawvote.voterName = $("#voter-name").val();
rawvote.babyName = $("#baby-name").val();
Hoist.apiKey("MYAPIKEY");
Hoist.post("vote", rawvote, 
  function (data) 
  { 
    window.location.href = "/voted.html";
  });

To get the Votes back:
Hoist.apiKey("MYAPIKEY");
var votes = Hoist("vote");
votes.get(function(data) { 
  html = []
  for(var i=0;i<data.length;i++) {
    html.push('<div class="row">');
    html.push('<div class="col-md-6">'+ data[i].date + '</div>');
    html.push('<div class="col-md-6">'+ data[i].babyName +'</div>');
    html.push('</div>); 
    }
  $("#results").append(html.join(""));
  });
As simple as that!