0

I have an app that allows users logged to add hiragana flashcards as favorites. When someone likes a flashcard, the flashcrad changed state as a grey heart to a red heart but the fullpage is reloaded. I try to understand Ajax to have only this action works on the page.

Here is the favorite controller

class FavsController < ApplicationController

  def index
    @favs = Fav.where(user: current_user)
  end

  def create
    @hiragana = Hiragana.find(params[:hiragana_id])
    @fav = current_user.favs.new(hiragana: @hiragana)
    if not @hiragana.favs.where(user: current_user).take
      @fav.save
    end
    redirect_to :back
  end

  def destroy
    @fav = Fav.find(params[:id])
    @fav.destroy
    redirect_to :back
  end
end

The view is a render I place on the hiragana flashcards

<% if current_user %>
  <div class="hiragana-fav">
    <% if hiragana.is_faved_by(current_user) %>
      <%= link_to fav_path(hiragana.is_faved_by(current_user)), method: :delete do %>
        <i class="fa fa-heart faved faved-on"></i>
      <% end %>
    <% else %>
      <%= link_to hiragana_favs_path(hiragana), method: :post do %>
        <i class="fa a fa-heart faved faved-off"></i>
      <% end %>
    <% end  %>
  </div>
<% end %>

Here is the css code :

.fa.faved {
  font-size: 18px;
  color: #d3d3d3;
  &-on {
    color: #FF0000;
  }
}

Thank you for your help.

I tried to do this in application.js (but it doesn't work) :

$(document).ready(function() {
   $('.faved-on').click(function() {
    var fav = $('.faved-off')

    $.ajax({
      type: "GET",
      url: "https://hello.co",
        success: function(data) {
      console.log(data);
      },
      error: function(jqXHR) {
      console.error(jqXHR.responseText);
      }
    });
  })
})
Hussein.
  • 179
  • 2
  • 11
  • Instead of `redirect_to :back` you have to `render json:` which will have the HTML in string which you want to replace . redirect_to: back will refresh the page. And for ajax you have to send json or html response only – Alankar More Feb 10 '16 at 13:15
  • @AlankarMore I change `redirect_to :back` => `render json: @fav`. Now when I want to add as a favorite there is a hash like this : `{ id: 40, user_id: 1, hiragana_id: 4, created_at: "2016-02-10T13:41:59.537Z", updated_at: "2016-02-10T13:41:59.537Z" }` – Hussein. Feb 10 '16 at 13:46
  • read about render_to_string [http://stackoverflow.com/questions/3714198/how-to-pass-variables-to-render-to-string] – Alankar More Feb 10 '16 at 13:57

0 Answers0