Like/Excuse button with AJAX

Asked

Viewed 666 times

1

On a certain page I have a button/link written "Bookmark"

<a href="SITE.COM/post/favoritar/ID" class="btn-favorite-normal">Favoritar</a>

Where the ID is the post id, but anyway, I already have a PHP script that takes care of entering into the database and remove.

when the post is favored or already marked as favorite, the script returns a JSON {"favorite:1"} and when it is not bookmarked or the bookmark tag is removed, the script returns {"favorite:0"}.

apart from these values I would like to change the status of the button with AJAX, for example: by clicking the favorite button, and everything occurs correctly, the script will return {"favorite:1"} and the name of the "Favorite" button will be "Favorite", the link(href), and the style class will also change to, ex:

<a href="SITE.COM/post/favoritar/ID/remover" class="btn-favorite-ativo">Favoritado</a>

was assigned to the URL, after the ID, the name "remove"; the name of the button has been changed to "favorite"; and the btn-Favorite-normal class has changed to btn-Favorite-active;

the "remove" in the URL you will remove from the bookmarks, which you click will return {"favorite:0"} and the button would return to its normal state, written "favorite" and with the default link to bookmark.

  • The correct is to return {Favorite:0} or {Favorite:1}

  • without the quotation marks?

  • Without the quotation marks... what is your backend language? if php vc can do this echo json_encode(array('Favorite' => 0)); or echo json_encode(array('Favorite' => 1));

  • yes, to using php, I was giving an echo "{Favorite:0}", this json function Ncode returned with quotes, {"Favorite":1}

  • Yeah, use it the way I pointed out:)

1 answer

3


Initially you need a handle of this button as vc will probably have several buttons like this we will use a class.. And let’s put an ID to represent the real object ID. Leave the link this way:

<a href="SITE.COM/post/favoritar/10" id="10" class="btn-favorite-normal favoriteLink">Favoritar</a>

Now we will create the events in Jquery, initially we will wait to load the document. And then we will create the routines.

<script>
//Espero o DOM ser carregado!
$(function() {
   //Detecto o clique no botão favoriteLink
   $('body').on('click', '.favoriteLink', function () {

       var objClicado = $(this); //Guardo o objeto em uma variavel porque ele não vai ficar disponível dentro do success do ajax.

       // recuperando qual é a url que tá dentro do link
       var url = objClicado.attr('href');
       var id = objClicado.attr('id');
       //Efetuando a chamada AJAX
       $.ajax({
           url : url,
           dataType: 'JSON',
           type: 'GET',
           beforeSend: function () {
              //Aqui vc pode colocar para mostrar alguma coisa enquanto carrega..
              objClicado.addClass("btn-favorite-loading");
           },
           success : function (retorno) {
               objClicado.removeClass("btn-favorite-loading");
               if(retorno.favorite == 1) {
                   objClicado.attr('href', 'SITE.COM/post/favoritar/'+id +'/remover');
                   objClicado.html('Remover');
               } else {
                  objClicado.attr('href', 'SITE.COM/post/favoritar/'+id);
                  objClicado.html('Favoritar');
               }
           },
           error : function (a,b,c) {
                objClicado.removeClass("btn-favorite-loading");
               alert('Erro: '+a['status']+' '+c);
           }
       });

       return false;

   });
});
</script>
  • The two if conditions are redundant because of the operator "==". One of them is enough.

  • So Paul I know that php does even I had not put, I wrote everything without testing so I left. But quiet, === compare typing

  • But vlw ae!! Edited.

  • Quiet. :-).

  • It returns me an Error: 0 Alert and then redirects to the page that checks if it is favorite.

  • Aaaaah I’m so sorry

  • missing a false Return

  • Error 0 occurs when the ajax request is canceled, that is because I did not give a false Return it called the ajax and redirected the redirect it canceled but now I have fixed the code.

  • Okay, I’ll test it

  • It worked fine, thanks, it is possible to put some effect "loading" while charging?

  • I am very lay in Js, but in the part of Beforesend, I realized that the script accesses the "html" of the code, I think the effect I want is to change the class of the button to change the stiglock while loading, something like class="btn-Favorite-loading" .... thank you

  • 1

    Ready changed the code and put an example of how to do.. If possible mark as right and click to give a point ok? Flww :)

  • I marked as solved :), I put addClass and then . html but did not change ....

  • objClicado.addClass("btn-loading"); objClicado.html("BIRLLLL");

  • issues an error in the console?

Show 10 more comments

Browser other questions tagged

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