5

I have an Ajax request from a page in my Rails app that looks like so:

$.ajax({
 type: 'POST',
 url: '/users/create/',
 data: "screen_name=<%[email protected]_name%>",
 success: createSuccessHandler,
 error: createErrorHandler,
 complete: hideLoadingImage
});

And currently the action responds with this:

respond_to do |format|
  format.js  { render :text => @user}
  format.html { redirect_to @user }
end

The create action works fine but how to I get the returned values (data) in my success method so I can do something like this?

function createSuccessHandler(data) {

    $("#div1").append(data.value1); 
    $("#div2").append(data.value2); 

}

Basically I'm trying to split the data up into different variables.

1
  • did you try to work with render :text => @user.to_json? Commented Feb 10, 2011 at 22:28

1 Answer 1

4

Return json in your controller (e.g., add a format.json stanza and request that instead of the .js one). Then in your createSuccessHandler function you'll do something like:

var foo = eval(data);
$("#div1").append(foo.value1); 
$("#div2").append(foo.value2); 

Note that some javascript libraries (like jQuery) provide safer ways to handle json than using eval, feel free to use those instead.

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

Comments

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.