Created
March 11, 2015 18:27
-
-
Save mayfer/14108f80bdd5022ec43d to your computer and use it in GitHub Desktop.
Simple Ajax Sinatra example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/json' | |
def get_click_data | |
{ | |
count: Click.count, | |
last_timestamp: Click.all.order('created_at DESC').first.created_at | |
} | |
end | |
get '/' do | |
erb :index | |
end | |
get '/num_clicks' do | |
json get_click_data | |
end | |
post '/click' do | |
puts params.inspect | |
Click.create | |
json get_click_data | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function() { | |
var updateClicks = function(response) { | |
var count = response.count; | |
var timestamp = response.last_timestamp; | |
var elements = $('<div>') | |
.append($('<div>').addClass('count').text(count)) | |
.append($('<div>').addClass('timestamp').text(timestamp)); | |
$('#counter').html(elements); | |
} | |
$('button').on('click', function(event) { | |
var data = { | |
some_data: "whatever", | |
} | |
$.post('/click', data).done(updateClicks).fail(function(response) { | |
console.log("ERROR!"); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment