Refresh with php

0

I have a button that adds the +1 value to the database and shows the total of likes the article already has.

 <a class='btn' href=portal/fav.php?id=".$produto['id']."> <span class='badge  bg-red'>".$produto['fav'] . "</span> <i class='fa fa-heart-o'></i> Likes  </a>

But this way the page will update. How do I, when I click the button, does it update without updating the page?

The page in php that does the update is

fav.php
    
asked by anonymous 03.09.2015 / 18:28

2 answers

1

You need to make an asynchronous request, known as AJAX. Using jQuery, it would look something like:

jQuery(document).ready(function($) {

    $('#fav-add').on('click', function(event) {
        event.preventDefault();

        produtoId = $(this).data('id');

        $.ajax({
            url: 'portal/fav.php',
            type: 'post',
            data: {id : produtoId},
            success: function(data) {
                alert('Sucesso!')
            },
            error: function() {
                alert('Erro!');
            }
        });

    });
});


<a class='btn' id="fav-add" data-id="<?php echo $produto['id'] ?>"> <span class='badge  bg-red'>".$produto['fav'] . "</span> <i class='fa fa-heart-o'></i> Likes  </a>

And with PHP you get the ID and do the treatment for the field update:

<?php

if(isset($_POST)){

    $id = $_POST['id'];

    $query = "UPDATE mytable 
      SET increment = increment + 1 
      WHERE id = $id";

  $this->execute($query);

}
    
03.09.2015 / 18:46
1

As in the example below you will call this function on the button, and on your fav.php page you mount the update, as there will be no return or alert or something can leave success empty even now if you want to do something after the update is just add on the success and the variable date you have the fav.php return

function atualizaLike(){
    $.ajax({
        url: "fav.php",
        method: "POST",
        data: {},
        async: false,
        success: function (data) {

        },
        error: function () {
            alert("Ocorreu uma falha ao verificar e tente novamente!");
        }
    });
}
    
03.09.2015 / 18:40