0

I'm creating this functionality where user can like a product and unlike it with javascript, if user likes the product it should add to the database and also if he unlike the product it should be deleted in database. Everything works fine in normal way but if I use javascript, the like button isn't working and either not adding anything in database same thing applies for unlike button. How can I make this work (like and unlike this should work in database too not changing the icons of like and unlike)?

Javascript

  // Like product
  function addToFavourites(productid, userid) {
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    method: 'post',
    url: `/product/like/${productid}`,
    data: {
        'user_id': userid,
        'product_id': productid,
    },
    success: function () {
        // hide add button
        $('#addfavourites' + productid).hide();
        // show delete button
        $('#deletefavourite' + productid).show();
    },
    error: function (XMLHttpRequest) {
        // handle error
    }
});



   // Unlike product
function deleteFromFavourites(productid, userid) {
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    method: 'post',
    url: `product/${productid}/unlike`, 
    data: {
        'user_id': userid,
        'product_id': productid,
    },
    success: function () {
        // hide add button
        $('#addfavourites' + productid).hide();
        // show delete button
        $('#deletefavourite' + productid).show();
    },
    error: function (XMLHttpRequest) {
        // handle error
    }
});

Route

  Route::post('product/like/{id}', ['as' => 'product.like', 'uses' => 'LikeController@likeProduct']);
  Route::post('product/{product}/unlike', 'LikeController@destroy')->name('product.unlike');

Blade File

  @if($product->isLiked)
  <div id="deletefavourite{{$product->id}}"onClick="deleteFromFavourites({{$product->id}}, {{ Auth::user()->id }})"> unlike </div>
   @else
   <div id="addfavourites{{$product->id}}" onClick="addToFavourites({{$product->id}}, {{ Auth::user()->id }})" > like </div>
@endif

How I add to favorite

    public function likeProduct($id)
{


    if(Auth::check()){
    $this->handleLike(Product::class, $id);
    return redirect()->back();
    }
    else{
        return redirect()->route('login')
    }
}

public function handleLike($type, $id)
{
    $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($id)->whereUserId(Auth::id())->first();

    if (is_null($existing_like)) {
        Like::create([
            'user_id'       => Auth::id(),
            'likeable_id'   => $id,
            'product_id'   => $id,
            'likeable_type' => $type,
        ]);
    } else {
        if (is_null($existing_like->deleted_at)) {
            $existing_like->delete();
        } else {
            $existing_like->restore();
        }
    }
}
7
  • Please check ajax call or not? Commented Nov 4, 2019 at 12:03
  • what do you mean? @Jinesh Commented Nov 4, 2019 at 12:05
  • When you click on like button it will call ajax or not? Commented Nov 4, 2019 at 12:20
  • when i click like i see this error on console 1(index):508 Uncaught ReferenceError: addToFavourites is not defined at HTMLAnchorElement.onclick @Jinesh Commented Nov 4, 2019 at 12:25
  • can you tell me where your write addToFavourites this function? If possible share your view files Commented Nov 4, 2019 at 12:30

3 Answers 3

2

I think you have not completed curly braces of function check my code

function addToFavourites(productid, userid) {
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    method: 'post',
    url: `/product/like/${productid}`,
    data: {
        'user_id': userid,
        'product_id': productid,
    },
    success: function () {
        // hide add button
console.log($('#addfavourites' + productid));
        $('#addfavourites' + productid).hide();
        // show delete button
        $('#deletefavourite' + productid).show();
    },
    error: function (XMLHttpRequest) {
        // handle error
    }
});

}

   // Unlike product
function deleteFromFavourites(productid, userid) {
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$.ajax({
    method: 'post',
    url: `product/${productid}/unlike`, 
    data: {
        'user_id': userid,
        'product_id': productid,
    },
    success: function () {
        // hide add button
console.log($('#addfavourites' + productid));
        $('#addfavourites' + productid).hide();
        // show delete button
        $('#deletefavourite' + productid).show();
    },
    error: function (XMLHttpRequest) {
        // handle error
    }
});
}
Sign up to request clarification or add additional context in comments.

Comments

0

first you must check in network for see request and response from inspect element this thing will make you can follow problem . you may have a problem with route so please check the network during post request.

Comments

0

First of all I suggest change routes. I mean, use same pattern for both actions: like and unlike

Route::post('product/like/{id}', ['as' => 'product.like', 'uses' => 'LikeController@likeProduct']);
Route::post('product/unlike/{id}', 'LikeController@destroy')->name('product.unlike');

Then inspect what you see on server, log incoming data. It should help to understand, why you algorithm didn't work.

Second, you have to render both div's in your blade template

   <div class="CLASS_SHOW_ITEM" id="deletefavourite{{$product- >id}}"onClick="deleteFromFavourites({{$product->id}}, {{ Auth::user()->id }})"> unlike </div>
   <div class="CLASS_HIDE_ITEM" id="addfavourites{{$product->id}}" onClick="addToFavourites({{$product->id}}, {{ Auth::user()->id }})" > like </div>

You have to choose class by value of attribute $product->isLiked

1 Comment

I see this error on console 1(index):508 Uncaught ReferenceError: addToFavourites is not defined at HTMLAnchorElement.onclick @Eugene

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.