Search code examples
javascriptjqueryruby-on-railsruby-on-rails-4ujs

How do I dynamically update a DOM element after an AJAX request if not using a `.js.erb`?


So I have a link/button that looks like this in my helper class:

link_to "UnFav", unfavorite_node_path(node), class: "btn btn-success favorite", method: :post, remote: true,  data: { toggle_text: 'Fav', toggle_href: favorite_node_path(node), id: node.id }

That calls these methods in my controller:

  def favorite
    @node.liked_by current_user

    if request.xhr?
      render json: { count: @node.get_likes.size, id: params[:id] }
    else
      redirect_to @node
    end
  end

  def unfavorite
    @node.unliked_by current_user
    if request.xhr?
      render json: { count: @node.get_likes.size, id: params[:id] }
    else
      redirect_to @node
    end
  end      

I am using acts-as-votable.

In my view, I show the number of votes on a particular node like this:

<span class="card-favorite-count">
   <i class="icon-heart"></i> <%= node.cached_votes_total %>          
</span>

Ideally, what I want to happen is, when one of those links are pressed, and the action is successfully executed, I want to update the count that is already being shown in the DOM.

I tried creating a favorite.js.erb and putting this in it:

$(".card-favorite-count").html('<%= node.cached_votes_total %>');

But I realized that when I favorited & unfavorited an item, in my server logs it never ever called that favorite.js.erb template - so this never gets executed.

I was also looking for a callback on the gem, but I can't find any.

What's the best way to approach this?


Solution

  • To render your file favorite.js.erb you need to do:

      def favorite
        @node.liked_by current_user
          respond_to do |format|
            format.js
            format.html{ redirect_to @node }
          end
        end
      end
    

    I think the if block would not be necessary still unsure but you can try the above code. It would respond with the js.erb when it is a js request and when it html request it will redirect.