Run PHP without updating the entire page

Asked

Viewed 2,398 times

3

My code is this:

<?php
$buscarusuario=$pdo->prepare("SELECT * FROM top5 WHERE status = 'ativo' ORDER BY colocacao ASC");
$buscarusuario->execute();

// Exibir com Fetch_Obj
$linha=$buscarusuario->fetchAll(PDO::FETCH_OBJ);
foreach ($linha as $listar) {

?>

<!-- INÍCIO TOP -->

  <div class="col-md-12 wow fadeInLeft" data-wow-duration="1000ms" data-wow-delay="300ms">
    <div id="top5-caixa">
      <div class="colocacao">
      <?php echo $listar->colocacao; ?>
      </div>
      <div class="musica-cantor">
        <p class="cantor"><?php echo $listar->cantor; ?></p>
        <p class="musica"><?php echo $listar->titulo; ?></p>
      </div>
      <div class="like">
        <a href='extra/likes.php?id=<?php echo "".$listar->id.""; ?>' alt="Gostei"><img src="images/like.png" height="40px" width="40px" id="like"></a>
      </div>

    </div>
  </div><!-- ./ COL-MD-12 -->
<?php } ?>
</div><!-- ./ ROW -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Inserir dados PDO</title>
</head>
<body>
<?php
// Incluindo arquivo de conexão
include("conexao.php");
$pdo = conectar();
// Recuperando valores
$id = $_GET['id'];

// Realizando consulta
$atualizartop=$pdo->prepare("UPDATE top5 SET likes = likes +1 WHERE ID='$id'");
$atualizartop->bindValue(":id",$id);
$atualizartop->execute();
if($atualizartop->rowCount() > 0):
    echo "Obrigado por votar!";
else:
    echo "Desculpe, mas ocorreu algum erro.";
endif;

?>

</body>
</html>

I wonder if clicking on the link to vote would return a "Thank you for voting!" without having to upgrade to the page that has the php function.

If anyone knows how to help, thank you.

  • To return this message, you must be sure that the recording was correct. For this, you have to have the script of the recording at the beginning of the program, not at the end, where you receive a message and in a div receive that message.

1 answer

4


Put a id in your image with the value like. In an extension file .js, goes that code:

$("#like").click(function(){
//evento de click sobre a imagem

    var id = $(this).attr('id'); //aqui você pegao valor do atributo id
    $dados['id'] = id; //esse array será passado para o php só que por POST ao invés de GET

    $.ajax({

        url: "incrementaLike.php", //Aqui vai o nome do seu arquivo PHP
        type: "post",
        async: true,
        data: $dados,
        cache: false
     })
     .done(function(data){

        //neste o ponto, o código php já foi executado e voltou para aqui se tudo ocorreu sem erro
        console.log(data);
     })
    .fail(function(){

        //vem para cá se algum erro ocorreu
        console.log("Deu alguma errada no php");
    });
});

You should separate your PHP into a separate file and the path to it goes in the attribute url.

In case I put a file called incrementaLike.php in the same folder as your html and also the archives js.

incrementaLike.php

<?php

include("conexao.php");
$pdo = conectar();
// Recuperando valores
$id = $_POST['id'];

// Realizando consulta
$atualizartop=$pdo->prepare("UPDATE top5 SET likes = likes +1 WHERE ID='$id'");
$atualizartop->bindValue(":id",$id);
$atualizartop->execute();
if($atualizartop->rowCount() > 0):
    echo "Obrigado por votar!";
else:
    echo "Desculpe, mas ocorreu algum erro.";
endif;

?>
  • Excuse me, I just forgot, in case you want to show a message, you must show inside the . done(), if something goes wrong, not logically in PHP, the function goes to . fail().

  • Hello Leandro. I appreciate your reply, but I unfortunately stayed floating here because I don’t know much about javascript. Could you make an example so you can understand? In the code I want to add the value of a column by clicking on the "like" image. I wanted to understand how to adapt to this function. Thanks in advance.

  • All right, first download this https://code.jquery.com/jquery-3.1.0.min.js file and add it to your page, it’s a library called Jquery.

  • I already have it in my code. Because some site functions need it. The problem is that I do not understand very well how javascript works

  • I changed the answer, I only changed the get for the post in your PHP

  • My friend you gave me a huge light. I understood how to work javascript now. But when I clicked on the image nothing happened. I put the id="like" in the image and pulled the <a> from the link I was using to update. What may have happened?

  • If you have a link that encompasses your image at the time you click it executes the default link event ignoring the image event, good luck with your ideas!

  • Always remember to end the issue to help the Stackoverflow community

Show 3 more comments

Browser other questions tagged

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