Dynamic like button

Asked

Viewed 341 times

0

next, on the page of each post has a button for "favorite", as I can check if the post has already been liked and change the name of the button to, for example, "favorite" and if it is not, when clicking the button would be done, but everything in the background, I have very shallow knowledge in javascript, but I know I will need ajax for this. I already built a small script in php/mysql that returns a json {"favorite":1} when the post is already favoured or when it is changed to favoured, being its natural state {"favorite":0}

As it is only possible to bookmark while logged in to the site, the user id will be captured by Session, and the post id will be sent through the method POST

Ex:

<a href="site.com/post/favoritar">Favoritar</a>

2 answers

1

Hello, I think for you to do ajax it would be good to use jQuery, I made a little code, to show you how to do the same.

    <a href="site.com/post/favoritar" id="favorito">Favoritar</a>

    <!-- Dependencias -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script>
        var btnFavorito = document.querySelector('#favorito');

        $(function(){

            alteraStatus();

            // altera texto do botão
            function alteraStatus(){
                var json = {"favorite":1,"userLogged" : true};
                if(json.userLogged){
                    if(json.favorite === 1)
                        btnFavorito.innerHTML = 'Favoritado';
                    else
                        btnFavorito.innerHTML = 'Favoritar';
                }
            }

            // Favoritar
            function favoritar(event){
                event.preventDefault();
                $.ajax({
                    url: "server.json"
                }).done(function(data){
                    console.log(data);
                    alteraStatus(data);
                });
            }
            $(btnFavorito).on('click',favoritar);
        });

    </script>

0

Do you save this favorite action in the database? If yes, just use Ajax on the page to check if the user has favorited the user id related item with the post id.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.