Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
An example of Sinatra working with Ajaxified JQuery based on some pieces of code published by Rafael George on the Sinatra Google Group.
require 'sinatra'
require 'dm-core'
require 'haml'
DataMapper.setup(:default, 'sqlite3::memory:')
class Message
include DataMapper::Resource
property :id, Serial
property :name, String
property :message, String
get '/' do
haml :app
post '/new' do
@message =
@message.message = "#{params[:will]} will #{params[:you]} you"
@@ app
%title Sinatra JQuery Test
%script{:type => 'text/javascript', :src => ''}
$(document).ready(function() {
$('#new_message').submit(function() {
$.post($(this).attr('action'), $(this).serialize(), function(data){
$('#message').append("<p>" + data + "</p>");
}, "text");
return false;
%h2 leave your message
%form#new_message{:action => '/new'}
%p{:type => "text", :id => "will", :name => "will"}
%strong will{:type => "text", :id => "you", :name => "you"}
%strong you
%input{:type => "submit", :value => "post!"}

This comment has been minimized.

Copy link

@sebastiangeiger sebastiangeiger commented Apr 9, 2011

Nice example! I had to add a require 'dm-migrations' to make it work (see my fork)


This comment has been minimized.

Copy link

@mol90 mol90 commented May 2, 2013

Hi, I'm doing a client (in javascript/jquery) and a server (in sinatra) that returns json object to clients when they do request html via $.get (). My problem is that I obtain the next error in the console's chrome (it also happen in other browsers):

XMLHttpRequest cannot load ..... Origin null is not allowed by Access-Control-Allow-Origin.

I know it's a security problem. I have tried to fix it with several solutions suggested in forums, but they don't work.
Could I tell me if you have been this problem? and how you fix it?

Thanks in advance!

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