Q:

jQuery not works on first click

I am using Rails and I am trying to create a bookmark icon in ajax.
The code works, the problem is on the first click the request is sent but the image doesn't change, for the next clicks the behavior is OK (request sent and image change).
My view:
<%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>
  <span class="favorite">
    <% if candidate.favorite %>
      <img src="<%= asset_url "favorite-activated.png" %>" alt="favorito" class="img-40" id="favorite_activated_<%= candidate.id %>">
    <% else %>
      <img src="<%= asset_url "favorite.png"%>" alt="favorito" class="img-40" id="favorite_<%= candidate.id %>">
    <% end %>
  </span>
<% end %>

My file favorite.js.erb
$('#favorite_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
    $('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');
  }
});

$('#favorite_activated_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
    $('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
  }
});

My controller:
def favorite
    @matching = @job.matchings.find(params[:matching_id]) 
    if @matching.favorite
      @matching.favorite = false
    else
      @matching.favorite = true
    end
    @matching.save
    respond_to do |format|
      format.html { redirect_to company_job_path(@job) }
      format.js  # <-- will render `app/views/company/jobs/favorite.js.erb`
    end
  end

Any idea?

A:

What I see from your code right now, that in your response you just setup listeners for click, while what you actually need to do is just to launch your code. You don't need listeners, because you've already setup them in rails itself:
<%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>

I think that changing your favorite.js.erb and setup just a part of code that you expect to be a callback:
$('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
$('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');

$('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
$('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');

should work for you. Hope this helps

