Dynamic tanking button

0

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

As you can only favor being logged into the site, the user id will be captured by session , and the post id will be sent via the POST >

Ex:

<a href="site.com/post/favoritar">Favoritar</a>
    
asked by anonymous 02.07.2016 / 05:03

2 answers

1

Hello, I think that for you to do ajax would be good to use jQuery, I made a small 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>varbtnFavorito=document.querySelector('#favorito');$(function(){alteraStatus();//alteratextodobotãofunctionalteraStatus(){varjson={"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>
    
02.07.2016 / 20:23
0

Do you save this favorite action in the database? If yes, it is only you to use Ajax on the page verifying if the user favored the related item the id of the user with the id of the post.

    
02.07.2016 / 19:21