Favorite facebook style button

Asked

Viewed 347 times

1

How to create a favorite Facebook like button that after clicking is marked and sends the request to the database in background, something like this:

inserir a descrição da imagem aqui

The First button is the normal state and the second is after being clicked and inserted into the database that the post was liked, all this in background without refresh, I’m doing this in a small MVC application, so as the background communication would be?

<a href="post/like/" class="btn_nornal">Favoritar</a>
  • About front, I can work in the back end, I just wanted to know how this communication would be, I don’t know anything about front rs

3 answers

1

You can use AJAX request to do this.

I suggest you create 3 classes for the button.

  • A class for the normal state (let’s say, default)
  • A loading class while the operation is still running in the background (let’s say, waiting)
  • A class of completed (let’s say, completed)

The script would be something like:

$("#favorite").on("click", function(){
   $("#favorite").addClass("esperando");
   $.post($("#favorite").attr("href"), {
      //aqui algum dado para ser enviado para o servidor
      id: "3213",
      user: "user1",
      data: new Date()
}).done(function(data){
   //Se retorno for ok, setar a classe do botao para concluido
   $("#favorite").addClass("concluido").
   $("#favorite").removeClass("default");
   $("#favorite").removeClass("esperando");
}).fail(function(data){
   //Se algo deu errado, setar botao para default novamente
   $("#favorite").removeClass("esperando");
   $("#favorite").removeClass("concluido");
   $("#favorite").addClass("default");
});
}

To improve management, it is interesting to save the value of $("#favorite") in some variable, so you don’t need to use the Jquery selector at all times.

1

There’s "n" ways to do this, but a simple way to get this by using jQuery is like this:

<a href="javascript:void(0);" class="btn_nornal">Favoritar</a>

In the example below it makes a request "autoload" ajax, when loading the page that checks the status:

  $(function(){
      var user_id = '123'; 
      //checa o status ao carregar a página...
       actionFavorite('checar', user_id);
      //favorita
       $('.btn_normal').on('click', function(){
          actionFavorite('favoritar', user_id);
       });
    });

    function actionFavorite(action, user_id) {
    $.post('check-or-add-status-favorite.php',{action:action, id:user_id},function(e){
           var statusClass = jQuery.parseJSON(e);
              if (statusClass.status == 'active') {
                 $('.btn_normal').addClass(statusClass.status);
                 $('.btn_normal').text(statusClass.txt)
              } else {
                 $('.btn_normal').removeClass('active');
                 $('.btn_normal').text(statusClass.txt)
              }
       });
    } 

and in PHP:

<?php
$action = $_POST['action'];
$user_id = $_POST['id'];
$status = 'active';
$txt = 'Favoritos';

if ($action == 'checar') {
   $consulta = $pdo->query("SELECT status_favorito
                            from usuarios
                            WHERE id_usuario=:id_usuario;");
   $consulta->bindParam(':id_usuario',(int) $user_id, PDO::PARAM_INT);
   $consulta->execute();
   $row = $consulta->fetch(PDO::FETCH_ASSOC);
    //se já for gravado, será: 'active', caso constrário, ele emprimirá ''; 
   if ($row['status_favorito'] == 'active') {
       $txt = 'Favoritos';
   } else {
     //reseta se não estiver ativo
     $status = '';
     $txt = 'Favoritar';
   }
   echo json_encode(array(
                     'status' =>  $status,
                     'txt' =>  $txt
                         ));
} else {
 //faz update se ação: 'favoritar'
 $consulta = $pdo->query("UPDATE usuarios SET
                           status_favorito=:status
                          WHERE id_usuario=:id_usuario;");
 $consulta->bindParam(':status',$status, PDO::PARAM_STR);
 $consulta->bindParam(':id_usuario',(int) $user_id, PDO::PARAM_INT);
 $consulta->execute();
 echo json_encode(array('status' => $status, 'txt'=> $txt ));
}
  • Just remember that this here (mix PHP in JS): var user_id = '<? php echo $user_id? >'; is a gambiarra.

  • Dude, this is a simple example, you can also pass in json,

  • I agree that there are "n" ways to do what he asked, but he could have made his code consume the variable of a Hidden or anything else that is less "gambiarra" than mixing PHP and JS. That’s just my suggestion, at no point did I say it would not work =)

  • the part that loads the ID, will be another implementation, I do not see the need for the demonstration of the answer in this case. It is irrelevant. It could be represented in various ways... even in an attribute of the element’s date-id type.

  • understand =) (no problem, his question is just how to submit the request, so I found it "irrelevant" to add a language other than JS in the answer).

  • I took it so as not to bother. Ok

  • In fact, checking with the button name would only be on the front end, something like: if the json generated by php returns true/1 to positive, that the post was added to the bookmarks ,javascript would change the class and the text of the button, otherwise a request would be launched and so change the status of the button, would not like to mix codes. Thanks for the comments!

Show 2 more comments

-1

Following Andrew’s line of reasoning, I’ve added some of the best practices.

I created this practical example, http://jsfiddle.net/2c6ok23e/4/ and hope to have helped.

Hug

Browser other questions tagged

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