Refresh with php

Asked

Viewed 79 times

0

I have a button that adds the value +1 in the database and shows the total of "Likes" that 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>

Only this way the page will update. How do, for when click the button, it update, without updating the page?

The php page that does the update is

fav.php
  • 2

    You will have to use a jQuery that does this... That accesses this fav.php, update and return with the updated number. Using json is very easy to do... I’ll see if I can find an example for you!

  • No answer solved the problem?

2 answers

1

The way in the example below you will call this function in the button, and in your page fav.php you mount the update, as you will have nothing to return or be an Alert or something like this can leave the Success empty even, now if you want to do something after the update just add it in Success and in the date variable you have the return of fav.php

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!");
        }
    });
}
  • This correct just call the function in onclick.

  • Having in my fav.php some successful and error snippets just for control, how do I ignore these messages?

  • your echo will be in the date variable of the Success so let’s assume that using an Alert would be, Success: Function (date) ? Alert(date); }

1


You need to make an asynchronous request, known as AJAX. Using jQuery, it would be 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);

}

Browser other questions tagged

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