mercredi 10 février 2016

Adding AJAX 'add to favorite' to have no full page reloading

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);
      }
    });
  })
})

Aucun commentaire:

Enregistrer un commentaire