views:

134

answers:

2

I am currently trying to use AJAX in my application via jRails. I am trying to return a JSON object from my controller, and then parse it in my Javascript. I am using json2.js to do the parsing.

Here is the code I currently have:

function getSomething()
{
    $.ajax({
        type: "GET",
        url: "map/testjson",
        success: function(data) {
            var myData = JSON.parse(data[0]);
            window.alert(myData.login);
        }
    });
}

and in the controller:

class Map::MapController < ApplicationController
  def index
  end

  def testjson
    @message = User.find(:all)
    ActiveRecord::Base.include_root_in_json = false
    respond_to do |w|
      w.json { render :json => @message.to_json }
    end

  end
end

The window.alert simply says 'undefined' (without tics).

However, if I change the javascript to window.alert(data) (the raw object returned by the controller) I get:

[{"salt":"aSalt","name":"", "created_at":"2010-03-15T02:34:25Z","remember_token_expires_at": null,"crypted_password":"aPassword", "updated_at":"2010-03-15T02:34:25Z","id":1,"remember_token":null, "login":"zgwrig2","email":"[email protected]"}]

This looks like an array of size 1, if I'm looking at it correctly, but I have tried just about every combination of JSON.parse on the data object that I can think of, and nothing seems to work.

Any ideas on what I'm doing wrong here?

EDIT This seems to work fine if there is more than one row in the Users table.

A: 

First sorry for me english.

I can see what you have 2 worng in your code.

Is better is you use $.getJSON to do json request.

  1. jQuery is yet a parser of json ... then in your callback funtion you only must do:

$(data).each(function(i, user){ // what you like do with a user });

  1. In your rails response there a error, is not a w.json { render :json => @message.to_json }, is only w.json { render :json => @message }. Whiout ".to_json".

I want what i help you.

Carlosvillu
I actually did remove the ".to_json" part, but it should be optional. The explicit callback function to handle each name value pair is also supposed to be optional...The odd thing is that my code works fine when there's more than one row being rendered into json.
Zachary
A: 

When there are more than one row, what you are deal is a String of your object in json format, not your json object representation. Really sorry for me english, i want explaind better ...

And if @message is a null object, because there isnt any messange, the render to json dont make anything, and when you are in your JS, you will have a problem because you dont have any response which worker. You must check your @message object. Maybe you can do that:

w.json {render :json => (@message.nil?) ? 0 : @checkpoint }

then, in your callback function you must check if your data response is "0" (like string) or one object.

Carlosvillu