Mike
Mike

Reputation: 91

Jquery, Ajax, Post Function, Rails

I am a Rails newbie and have a question about posting from ajax to a rails controller, and returning the data to javascript. I'm pretty unfamiliar with how this actually works, but I've pieced together a working post function from other SOF threads. Right now, I'm posting the data from a simple button click, and the ajax code looks like this:

$.ajax({
  type    : 'POST',
  url     : "http://localhost:3000/fbusers", 
  data    : { tester : { name : 'boom' } },
  success : function(data) {
              alert(data);          
            },  
});

Here is the code in the controller, its pretty simple:

def create
  @user = User.create( params[:tester] )
end

This code works fine to post the data to the create function, which creates (posts?) the entry to the db. But I would like to return the data in the alert function upon "success." But right now, the alert just returns object[object]. Can anyone help me pass the post data into the alert function? If possible, an explanation (or direction to a basic tutorial) would be extremely helpful as well.

Thanks in advance!

Upvotes: 3

Views: 2700

Answers (1)

nambrot
nambrot

Reputation: 2571

I assume you want to return the user. In this case i recommend:

def create
  @user = User.create( params[:tester] )
  respond_to do |format|
    format.html
    format.json  { render :json => @user}
  end
end

And then just make the ajax call request the json

Upvotes: 3

Related Questions