Function of "Like" without reloading the page?

Asked

Viewed 642 times

2

Hello, good afternoon!

I’m having a problem that I don’t know how to solve. I don’t know how to program in Jquery or Ajax, but I intend to start learning. How can I make the following PHP code work in Ajax or JS? Which of the two options is better to perform this action of "Like"?

<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>

Code of the like-post page:

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 with that button as soon as clicked it add one more likes to the post. Thanks in advance!

1 answer

1


Well, I’m gonna give you that strength :

We can remove 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>

php file (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
        }
    })
})
  • Thank you very much! But like I said, I don’t understand almost anything about js (basics). How can I return the Ikes to a certain div?

  • The code I’m using is an echo $post['Likes'] inside a div with the class "Likes"

  • @Joãovictorvalentim I edited, then response is numeroDeLikes

  • Sorry, I still can’t understand. Inside the Success part in the js file I need to put something? And this variable number I put inside the div where I want the Ikes to appear, right? Because I used the code above but it turns out that this variable is not defined..

  • @Joãovictorvalentim you assign the total of Ikes that comes from your bank to her, edited with a fixed value.

  • I haven’t gotten it yet :/ But thanks for the help. I’m going to start a study in Ajax and Jquery to improve it

Show 1 more comment

Browser other questions tagged

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