Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get Rails variables from my returned jQuery Ajax data?

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.

like image 262
Lee Avatar asked Oct 11 '22 16:10

Lee


1 Answers

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.

like image 185
cam Avatar answered Oct 15 '22 11:10

cam