views:

671

answers:

2

I have a very simple sinatra site that I'm trying to access via ajax through jQuery.

To keep things incredibly simple, this code snippet:

get '/behavior_count' do
  "60"
end

which returns "60" in the browser, shows up as an empty string when attempting to access the site via $.get in jQuery. The strange part is in Firebug, while the Response is empty, the HTTP header correctly describes Content-Length as 2, and I can see the request show up on the server.

Is there something specific to Sinatra that isn't returning my data, or am I not using jQuery correctly?

If it helps, I also tried this code:

get '/behavior_count' do
  content_type 'text/plain', :charset => 'utf-8'
  "60"
end

and my jQuery looks like

$.get('http://mysite:4567/behavior_count'); // Ignore the response, but
                                            // watch the request in firebug

Any ideas?

+3  A: 

Until someone comes up with a proper answer, here's the minimal example I tried and it works:

test.rb:

require 'rubygems'
require 'sinatra'

get '/' do
  haml :test
end

get '/howmany' do
  "42"
end

views/test.haml:

%html
  %head
    %script{:type => "text/javascript", :src => 'js/jquery.js'}
    :javascript
      $(document).ready(function() {
        $('#btn').click(function(event){
          $.get('/howmany', function(data) {
            $('#answer').html(data);
          });
        });
      });
    %title Test page

  %body
    %input#btn{:type => 'button', :value => 'How many?'}
    #answer

(there's also public/js/jquery.js, of course)

Mladen Jablanović
+1  A: 

It's probably not a Sinatra / Jquery interaction problem... Instead, it's an Ajax "cross domain security" problem.

Your original problem could be due to the fact that you've got your form and your server hosted on different domains. XMLHTTPRequests (Ajax) [.get .post .ajaxForm .ajaxSubmit] will fail if they are on different domains. Check your logs on the app that receives the post, and you might see something like (in the log file) "OPTIONS behavior_count" 404 Basically, it will work when you hit the app directly, but when you try to use AJax to do it, and that Ajax is accessing it from a different domain (i.e., the "action" option on the form has "http://some.differentdomain.com/behavior_count" in it).

That would explain why you're simple example works (the form and the post are happening on the same application / same domain).

I had the same problem for 5 hours just now... I wanted to use a generic "comments" application and have other applications be able to post to the one central application (on a different domain). It won't work. But then I made the 2 applications into 1, and everything was fine. Alternately, you can try to use JSONP to make it work and still keep the 2 applications separate.

I read this, which helped: http://stackoverflow.com/questions/1099787/jquery-ajax-post-sending-options-as-request-method-in-firefox

Good luck! -Greg

Greg Edwards