Function of "Like it" without reloading the page?

2

Hello, good afternoon!

I'm having a problem that I do not know how to solve. I do not know how to program in JQuery or Ajax, but I intend to start learning. How can I do to make the following code in PHP work in Ajax or JS? Which of the two options is best for this "Like" action?

<li>
      <form action="like-post.php" method="post">
      <button name="id" value="<?= $post["id"] ?>" class="like-post">Like</button>
      </form>                     
</li>
<li class="likes">
      <?php 
      echo $post["likes"];
      ?>
</li>

Like-post page code:

include("header.php");
include("conecta.php");
include("functions.php");

   $id = $_POST['id'];
   like($conecta, $id);
   header("Location: index.php");
   die();

What I want to do is that this button as soon as it clicks it adds another tanned to the post. Thank you in advance!

    
asked by anonymous 22.02.2017 / 18:16

1 answer

1

Well, I'm going to give you this hint:

We can take the form, since it will be asynchronous.

<li>
  <button name="id" data-id="<?= $post["id"] ?>" class="like-post">Like</button>  
</li>
<li class="likes" id="<?= $post["id"] ?>">
    <?php 
  echo $post["likes"];
  ?>
</li>

File php (like-post.php):

<?php
     echo "123";//esse é o retorno da requisição
?>

Now the Script

//Quando clicar nos botões com nome id
$( 'button[name="id"]' ).click(function(){
    var that = $( this );
    var valId = that.data( 'id' );

    that.prop('disabled',true);// Evitar overposting com os usuários de dedinho nervoso

    $.ajax({//requisição
        url : 'like-post.php', //url (duuhh)
        data : { id : valId }, //informações que vão no corpo da requisição
        success : ( response ) => { 
           //faça alguma coisa com o retorno, pode até ser passar o total de likes pra uma div
          console.log(response); //123
          $( '#'+valId ).html( response );// carrega dentro da <li>

        },
        error : () => {//se der erro no php
            that.prop( 'disabled',true );//deixa o usuário dedar denovo
        }
    })
})
    
23.02.2017 / 14:42