Javascript going to the top of the page?

0

Galera, I have a "Like" script, but when I click on it, the page is half reloaded and goes to the top. But when I actually reload the page, it goes to the place I clicked to give the "Like". What can this be?

Everything is working properly, the part of the tanned count, add the tanned in the database and everything else .. What happens even is this "bug" that the page does not continue in the same place after I click the button of "Like".

Script:

function add_like(post_id, hora_post){
    $.post("init/add_like.php", {id_post:post_id, post_data:hora_post}, function(dados){
       if(dados == 5){
           get_like(post_id, hora_post);
       } 
    });
}
function get_like(post_id, hora_post){
    $.post("init/get_like.php", {id_post: post_id, post_data:hora_post}, function(valor){
        $('#post_'+post_id+'_like').text(valor);
    });
}

Page add_like.php:

session_start();
include("../functions.php");
include("../conecta.php");
$post_id = $_POST['id_post'];
$hora_post = $_POST['post_data'];
if(!verificar_clicado($conecta, $post_id, $_SESSION['id'])){
    if(adicionar_like($conecta, $post_id, $_SESSION['id'], $hora_post)){
        echo 5; // Valor para ser enviado para o arquivo JS 
    } 
}

get_like.php page:

session_start();
include("../functions.php");
include("../conecta.php");
$post_id = $_POST['id_post'];
$numero_de_likes = retornar_likes($conecta, $post_id);
echo $numero_de_likes;

Like button:

 <a href='' name="id" onclick="javascript:
            var dado1 = '<?=$post['id']?>';
            var dado2 = '<?=$post['hora']?>';
            add_like(dado1,dado2);
            " class="like-post">Like</a>

Likes button:

<span id="post_<?=$post['id']?>_like">
                                <?php
                                    if($post['likes'] == 0){

                                    } else {
                                        echo $post['likes'];
                                    }
                                ?></span>
    
asked by anonymous 26.02.2017 / 19:14

2 answers

3

Swap the anchor of the liking button for a span. The blank href is what is causing a scroll to the top of the page.

    
26.02.2017 / 21:43
0

If you want to continue using html anchor tagging ( <a href="#">...</a> ) you can simply use a return false; at the end of your function.

Example:

function add_like(post_id, hora_post){
    $.post("init/add_like.php", {id_post:post_id, post_data:hora_post}, function(dados){
       if(dados == 5){
           get_like(post_id, hora_post);
       } 
    });
    return false;
}
    
27.02.2017 / 20:47