Angelo Chrysoulakis
Angelo Chrysoulakis

Reputation: 946

Working with json response from rails

I'm almost there but can't seem to debug this simple item.

I have page with:

<div id="count">

I am using the following function to get the count from the server:

$.get("/count?post_id=" + postId, function(post_count) {
    $('#count').html(post_count.count);

And the response from the server is:

[{"count":0}]

But, the page does not update with the count supplied. I used to have the response render simple text and the page was updating with the new count as expected but I can't get it to work when using json.

Can anyone please lend a hand?

EDIT 1

When I do

alert(post_count)

I get an alert dialogue with [object][Object]

However, when I try to do

alert(post_count.count)

I get an alert dialogue with Undefined.

Is the JSON format as noted above correct?

Upvotes: 1

Views: 322

Answers (2)

Gary S. Weaver
Gary S. Weaver

Reputation: 8096

If the response is [{"count":0}] then it looks like:

post_count.count

should be:

post_count[0].count

since it is an array containing an object/hash.

Also, consider using existing frameworks like restful_json and AngularJS to do the heavy lifting once you go beyond simple calls like this. An example of using those two projects together is the employee-training-tracker app. There other Javascript frameworks that also hide this sort of complexity. Some are listed in the TodoMVC page with examples. And, look into using rails-api if you write your own service controllers.

Upvotes: 2

Novae
Novae

Reputation: 1171

Make sure the Rails application response with JSON, not only in the content but also the headers:

try:

respond_to do |format|
  format.json { render :json=> whatever.to_json }
end

Edit: Missed this before but when calling JSON with jQuery to have it automagically parse(instead of using JSON.parse(response) use:

$.getJSON(url, function(){});

Upvotes: 1

Related Questions