facebook style button

1

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

Thefirstbuttonisthenormalstateandthesecondisafterbeingclickedandinsertedintothedatabasethatthepublicationwastanned,allinthebackgroundwithoutrefresh,IamdoingthisinasmallMVCapplication,thenwhatwouldbethecommunicationbybackground?

<ahref="post/like/" class="btn_nornal">Favoritar</a>
    
asked by anonymous 27.06.2016 / 18:58

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, done)

The script would look 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's worth saving the value of $("#favorite") to some variable, so you do not need to use the JQuery selector at all times.

    
27.06.2016 / 19:36
1

There are " n " ways to do this, but a simple way to get this by using jQuery looks like this:

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

In the example below it makes a "autoload" ajax request by 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 ));
}
    
27.06.2016 / 22:05
-1

Following Andrew's line of reasoning, I've added some good practice.

I've created this working example, link , and hope to have helped.

Embrace

    
27.06.2016 / 20:56