javascript - How to keep favorite / unfavorite button color after page reload? ← (PHP, Laravel, JavaScript, JQuery, HTML)

I'm working on a Laravel project where user can favorite and unfavorite books, when user clicks on favorite button , the color changes to red and when clicked again it's color back to gray , in the two cases the DB changes successfully without page reloading as i used ajax , but the problem now is that when i refresh the page, the button back to gray color.

here is the code of my view: // i removed most html code

                     @foreach( $books as $book)
                              <div class="mb-3">
                                <span class="badge badge-pill badge-primary p-2 mr-4">
                                  <span class="count_of_book">{{ $book-> amount }}</span>
                                  copies available
                                </span>
                               <i id="favorite" data-bookid="{{ $book-> id }}"  class="fas fa-heart fa-2x"></i>
                          </div>
                        </div>
                        @endforeach
                  // ajax link      
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
            <script>
            var token = '{{ Session::token()}}';
            var urlFav = '{{ route('favor') }}';
            </script>

and the code of js:

        $(".fa-heart").on("click", function (event){
            bookid = $(this).data("bookid");
            $.ajax({
                method: 'POST',
                data: {bookid: bookid , _token:token},
                success: function(data){
                    if(data.is_fav == 1){
                        $(event.target).toggleClass('heart-active');
                    }
                    if(data.is_fav == 0){
                        $(event.target).addClass('text-dark');
                    }
                }

            });

and the php code on controller:

         public function bookFavBook(Request $request){
                $book_id = $request['bookid'];
                $fav = DB::table('favorites')
                ->where('book_id', $book_id)
                ->where('user_id', Auth::user()->id)
                ->first();

                if(!$fav){
                    $newfav = new Favorite;
                    $newfav->book_id =$book_id; 
                    $newfav->user_id = Auth::user()->id;
                    $newfav->fav = 1;
                    $newfav->save();

                    $is_fav = 1;
                }
                elseif ($fav->fav == 1){
                    DB::table('favorites')
                ->where('book_id', $book_id)
                ->where('user_id', Auth::user()->id)
                ->delete();

                $is_fav = 0;
                }
                elseif ($fav->fav == 0){
                    DB::table('favorites')
                ->where('book_id', $book_id)
                ->where('user_id', Auth::user()->id)
                ->update(['fav'=> 1] );

                $is_fav = 1;
                }

                $response = array(
                    'is_fav'=>$is_fav,
                );

                return response()->json($response, 200);
            } 
        }

and finally the route used :

Route::post('/favor', [ 'uses'=>'BookController@bookFavBook','as'=>'favor']);

please any one can help, i just want to keep button color even after page reload and every time user log in. thank you

Answer



Solution:

You need to get the favorite books list and loop through the list to compare with the books. Below code gives you the idea,

@foreach( $books as $book)
  @foreach($favBooks as $fav) // Pass Favorite books list from controller.
  <div class="mb-3">
    <span class="badge badge-pill badge-primary p-2 mr-4">
      <span class="count_of_book">{{ $book-> amount }}</span>
         copies available
      </span>
    <i id="favorite" data-bookid="{{ $book-> id }}" class="fas fa-heart fa-2x {{ $fav->bookid == $book->id ? 'heart-active' : 'text-dark'}}"></i>
   </div>
   @endforeach
@endforeach

Source