Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
basic ajax/sinatra example
$:.unshift File.expand_path(File.dirname(__FILE__))
require "viz"
run Sinatra::Application
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
get '/' do
erb :index
get '/follower_viz' do
@user = params[:user]
erb :follower
get '/repo_viz' do
@user = params[:user]
erb :repo
@@ index
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(function (){
//this happens if form is submitted
//prevent the default behavior of a form (it should do nothing in our case)
//send an ajax request to our action
url: "/follower_viz",
//serialize the form and use it as data for our ajax request
data: $(this).serialize(),
//the type of data we are expecting back from server, could be json too
dataType: "html",
success: function(data) {
//if our ajax request is successful, replace the content of our viz div with the response data
//show the link to the repo_viz (don't forget: we are still in the submit event!)
$('#viz_link').append($("#viz_form input:first").val());
//this happens if we click our new shiny link with the submitted username in it
//do you remember?! :)
url: "/repo_viz",
data: "user="+$("#viz_form input:first").val(),
dataType: "html",
success: function(data) {
<form action="/" method="post" id="viz_form">
<label>Enter your username:</label>
<input name="user" type="text">
<input type="submit" value="Do it!">
<p id="viz_p" style="display:none;"><a id="viz_link" href="#">click here if you want to see the awesome repo_viz for </a></p>
<div id="viz" style="margin:20px;border:1px dashed black;height:400px;">
@@ follower
<p>here comes the crazy follower_viz for <%= @user %></p>
@@ repo
<h1>this viz from <%= @user %>'s repos is HUGE!</h1>
Copy link

jangho commented Apr 13, 2015


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment