1

I have some experience with RoR, although, I'm kind of a newbie in AJAX matters. My goal is to have a HTML5 + JavaScript client and a Ruby on Rails server running in different machines (eventually).

What I want is the JavaScript client to get contents from the server in JSON format, to be parsed afterwards. I already tried a bunch of things, like adding a "responseType", etc, but non of them worked.

My current JavaScript file is like this:

$(document).ready(function() {
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", "http://localhost:3000/contents", true);
      xmlhttp.send();

      alert(xmlhttp.responseText);
});

And my RoR app has a path "/contents" that calls the index function of contents_controller.rb, that is like this:

def index
    @contents = Content.all.order('created_at DESC')

    respond_to do |format|
        format.html # index.html.erb
        format.json { render json: @contents }
    end
end

Is AJAX even the correct way to do this? I'm a bit lost.

Thanks a lot!

1
  • Why are you using vanilla js methods when you have jQuery? Look at $.ajax. Whether or not ajax is the correct way of doing this is upto you to decide I think. Commented Jun 9, 2014 at 11:15

2 Answers 2

3

With jQuery, you can do it like this.

$.ajax({
  url: '/contents',
  type: 'GET',
  dataType: 'json',
  beforeSend: function (xhr) {
      xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  },
  success: function(data){/* do something meaningful with data */},
  error: function(xhr, status, response) {/* your error callback */}
});

Your format.json shall handle your responses.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Just changed the 'url' to add '.json' and it was all fine. Thanks a lot!
1

You can simply call /contents.json (add .json with every url to get output fron json template) or Set your default format as json if you never need html view. For that ...

You can modify your routes.rb files to specify the default format.

routes.rb

resources :contents, defaults: {format: :json}

3 Comments

I didn't know about that .json to get the json template. Thanks! But I tried to add ".json" to the above JavaScript code and I still get an empty answer...
You need to have template for json output. Like index.html.erb is rendered for html, similarly index.json.jbuilder will be rendered for json request. You can see json template in one of your scaffolds (or generate a scaffold and see /my_scffold_name.json works)
Jbuilder is another DSL language

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.