Michael Durrant
Michael Durrant

Reputation: 96454

How to get rails to use ajax to update an HTML table row after the db update?

I have a table of content with multiple rows.
For any given row I want to be able to verify a record and have that be reflected immediately on the screen by changing the "verify link" hyperlink to be just plain text 'verified'.
Seems like a fairly common pattern for others.

I have the following markup:

...# (table stuff).
 = link_to 'verify', verify_link_path(:id => link.id),  class: 'verify', remote: true

This (successfully) calls the links controller 'verify_link' method:

def verify_link
  @link = Link.find(params[:id])
  # Ignore additional verify logic for now, just set as verified (when the user clicks verify).
  @link.verified_date = Time.now
  @link.save!
  respond_to do |format|
    format.js
  end 
end

I know this works... because the database gets updated.

Finally I want to update the page (table-row-cell) to reflect this. This is where I am stuck.

The controller method successfully calls the following app/views/links/verify_links.js.erb file:

$(function() {
$(".verify")
  .bind("ajax:success",function(event,data,status,xhr) {
    this.text='verified';
    alert("The link was verified.");
  });
});

I know it gets invoked... because I can put alert("hello world"); at the start and it gets displayed as a pop-up.

The part that isn't working is replacing the 'verify' link with plain text 'verified'. Actually I can't even the alert to work in there at all. Nothing gets updated in the ui. On the backend the change in the db is made however, so if I refresh the page I do see the change reflected at that point).

Notes:

Upvotes: 2

Views: 1917

Answers (1)

Mandeep
Mandeep

Reputation: 9173

@hjing is right. The code inside app/views/links/verify_links.js.erb is already a response to your ajax. You need not bind it to the ajax:success.

As you suggested you need to make an id for each link which you'll have to munge from the table row id or number. For example for your your links will look like this:

= link_to 'verify', verify_link_path(:id => link.id),  class: 'verify', id: "verify_#{table_row_no}", remote: true 

then inside your app/views/links/verify_links.js.erb you can target that particular link like this:

$("#<%= j 'verify_#{table_row_no}' %>").text("verified");
$("#<%= j 'verify_#{table_row_no}' %>").prop("href","#"); #you would also want to change the href in case someone clicks it again

Upvotes: 4

Related Questions