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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With