2

I'm new to Rails so this is really basic and I'm sure I'm missing something simple. I'm trying to send some JSON to an action and get it to return a response in JSON. A simplified version of what I'm trying is below.

The jQuery I'm using:

var request = { 'voter': { 'voter_name': 'John', 'voter_email': '[email protected]'} };

var url = 'http://someip/Voters/create';

$.ajax({
    type: 'POST',
    url: url,
    data: request,
    success: function (data) { alert(data); },
    error: function (data) { alert(data); },
    dataType: 'json'
});

My action:

def create
    @voter = Voter.new(params[:voter])

    logger.info(@voter.to_json)

    render :json => @voter
end

It seems like this should be returning just fine, especially considering the console is showing the Voter object just fine:

Processing VotersController#create (for someip at 2010-08-17 21:19:51) [POST]  
Parameters: {"voter"=>{"voter_name"=>"John", "voter_email"=>"[email protected]"}}
{"voter":{"created_at":null,"updated_at":null,"voter_email":"[email protected]","voter_name":"John"}}
Completed in 11ms (View: 1, DB: 0) | 200 OK [http://someip/Voters/create]

The problem is that my alerts (or any other way I try to look at this data) are all showing me null. No object is being returned. Any pointers would be greatly appreciated.

8
  • what do you see if hit that action with curl? Is the response empty? Commented Aug 17, 2010 at 23:35
  • I'm stuck on a windows box at the moment so that's a very good question. If I access that action directly in my browser with a GET I'm seeing: {"voter":{"created_at":null,"updated_at":null,"voter_email":null,"voter_name":null}} Commented Aug 17, 2010 at 23:44
  • Is the url you're posting to on a different domain from the page doing the posting? Commented Aug 17, 2010 at 23:58
  • It's actually all by IP at this point. It will be different domains eventually. What's weird is the server is definitely getting the POST though since I've even had it write to sqlite. It's just not responding with anything. Commented Aug 18, 2010 at 0:00
  • Could you include a snippet from your development log that shows the POST request hitting your create action? Commented Aug 18, 2010 at 1:00

1 Answer 1

1

I think you need to convert the instance to JSON before rendering. Like this:

render :json => @voter.to_json

Just like you do in your debug log output.

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

1 Comment

Thanks for the response. I tried that and it didn't seem to make a difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.