Associate an ajax request with a specific Rails 3.1 element

I have a list of users, each of which has a "follow" button next to their name. The follow request completes via ajax, and the Next button goes to unfollow.

My code works fine with one registered user (and also works with several listed users), but I would like to specify several users, and then somehow bind the following request to a specific ".follow_form" element, which each button is contained inside, so that only one “follow” button that is pressed changes to “unfollow”.

The jquery code I am having a binding problem with is as follows:

/create.js.erb $(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>") 

and

  /destroy.js.erb $(".follow_form").html("<%= escape_javascript(render('users/follow')) %>") 

When the form is presented explicitly, all .follow_form elements are changed, but I cannot figure out how to link the correct element?

One of the few code snippets I tried (for create.js.erb) was:

  $("input.follow").bind( function() { $(this).closest(".follow_form").html("<%= escape_javascript(render('users/unfollow')) %>") }); 

But no answer

+2
source share
1 answer

You should probably do this in the ajax:success callback, as it is automatically bound to the object.

You can delete these .js.erb files and just visualize them in the controller:

 def create # creation code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/unfollow' ) }, :status => :created end def destroy # deletion code here # now render the response render :json => { :new_button => render_to_string( :partial => 'users/follow' ) }, :status => :no_content end 

Then in your javascript file:

 $('input.follow, input.unfollow').live('ajax:success', function(data, json, response) { $(this).closest(".follow_form").html(json.new_button); }); $('input.follow, input.unfollow').live('ajax:error', function(data, xhr, response) { // handle the ajax error here }); 
0
source

All Articles