Skip to content

Instantly share code, notes, and snippets.

@stujo
Last active August 29, 2015 14:07
Show Gist options
  • Save stujo/95d13a0aec2faebc2b9b to your computer and use it in GitHub Desktop.
Save stujo/95d13a0aec2faebc2b9b to your computer and use it in GitHub Desktop.
Mini Ajax Sinatra Example - A single file demonstrating Ajax with HTML Fallback
require 'sinatra'
require "sinatra/json"
def eight_ball
[
"Definitely",
"Most likely",
"Try again",
"Cannot predict now",
"Don't count on it",
"Yes",
"No",
"For Sure"
].sample
end
get '/' do
<<-eos
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<form action="/answer" method="POST">
<input id="button_go" value="Ask the Eight Ball" type="submit"/>
</form>
</body>
<script>
$("#button_go").click(function(event){
event.preventDefault();
var promise = $.post('/answer', {
dataType: 'json'
});
promise.done(function(data){
alert(data.answer);
});
});
</script>
</html>
eos
end
post '/answer' do
pass unless request.xhr?
json({ :answer => "Ajax says '#{eight_ball}!!'" })
end
post '/answer' do
<<-eos
<html>
<body>
<div>HTML says '#{eight_ball}!!'</div>
<div><a href="/">Ask Again!</a></div>
</body>
</html>
eos
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment