Using $ (this) in a .js.erb file - Ruby on Rails AJAX

I am using Rails3 with jQuery and trying to make simple ajax calls. I have a link that displays the current status (online / offline) of the application. Clicking on it will update the status.

link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status"}

live_status.js.erb:

$(this).fadeOut();
$(this).parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$(this).fadeIn();

status_link will return updated link_to

However, $ (this) does not work as I imagine. How to update click status with new status?

+3
source share
2 answers

you must use a selector. When you have the code that is interpreted in the ajax answer, jQuery does not know that you are "this". Better use something like:

$('#my-special-div').fadeOut();
$('#my-special-div').parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$('#my-special-div').fadeIn();
$('#my-special-div').hide(2000, function () {
    $(this).remove();  // here jQuery knows you are talking about 'my-special-div'
});
+3
source

You must specify the element that you want to update the ID (I added the element to the hash at the very end):

link_to app.status, { :controller => :apps, :action => :live_status, :id => app }, {:remote => true, :class => "#{app.status} status", :id => app.id}

, jQuery:

$("#<%= @wowza_app.id %>").fadeOut();
$("#<%= @wowza_app.id %>").parent().html("<%= escape_javascript(status_link(@wowza_app)) %>");
$("#<%= @wowza_app.id %>").fadeIn();

, , @wowza_app id, , , .

+8

Source: https://habr.com/ru/post/1794036/


All Articles