WagnerMatosUK
WagnerMatosUK

Reputation: 4429

How to use respond_to for json?

I'm a bit confused: I'm writing a centralised controller as per this question and am getting a bit confused on the respond_to method works.

In a API::Controller I'd have something like this:

def index
  @post = Post.all
  render json: @posts
end

And on the js (AngularJS) side of things I'd have something like this:

$http.defaults.headers.common.Authorization = 'Token token='+ $scope.user.auth_token;

$http.get('/api/posts').success(function (data) {

  $scope.posts = data;

});

That works fine on the API controller, however I want to use a shared controller:

def index
  @post = Post.all
  respond_to do |format|
    format.html { render layout: 'admin' }
    format.json { render json: @invoices }
  end
end

But when I try to do the an ajax call it seems the API is responding with html rather than json.

What am I missing?

Upvotes: 1

Views: 1385

Answers (1)

Arslan Ali
Arslan Ali

Reputation: 17802

Append .json at the end of the URL you are trying to hit with. This way, server will know that request is demanding data in JSON format, while the default format is HTML.

If you are using jQuery to do AJAX, and want to receive data back in JSON format without appending .json at the end, you can use then use the function $.getJSON(), or can pass simply the option dataType: "json" in $.jquery() function call:

$.ajax({
    dataType: "json", // To receive data back in JSON
    url: url,
    data: data,
    success: success
});

Upvotes: 2

Related Questions