lundi 4 novembre 2019

Ajax the button is not changing until refreshing page

If I click the like or unlike button it sends the data and works as expected but the problem is it doesn't change the button instantly when you click until I refresh the page. eg. when I click like button it should change to unlike, I don't see errors in console, I have seen some questions similar to this but they haven't solved my problem. Any help would be appreciated.

Javascript

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).show();
        // 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).show();
        // show delete button
        $('#deletefavourite' + productid).show();
    },
    error: function (XMLHttpRequest) {
        // handle error
    }
});
}

Blade File

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


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire