简体   繁体   中英

Like button without refreshing whole page

I have create a like button in my site. It is done using PHP. When someone clicks on like, it will increment the count and changes it to 'unlike'. Similarly when click unlike the count decrements.

The problem is when click on the like button the whole page refreshes. When clicked like,it goes to a page 'like.php' which will do the increment, decrement and other operations and then come back to previous page. I heard that with ajax/jquery it is possible to refresh a div without reloading the whole page. How can i do it. I am new to ajax/jquery.

$.post( "ajax/test.html", function( data ) {
    $( ".result" ).html( data );
});

https://api.jquery.com/jQuery.post/

You can use .click for click events. http://api.jquery.com/click/

assuming your like button has the attribute class="like" and your unlike button has the attribute class="unlike"

something like this should do the trick:

$(function() {
    $like = $(".like");
    $unlike = $(".unlike");

    if ($like.length) {
        $like.on('click', function() {
            $.ajax('like.php', { data: 'here' }, function(response) {
                // do something with your response from like.php:
                $like.addClass("unlike");
                $like.removeClass("like");
                $unlike = $like;
            });
        });
    }

    if ($unlike.length) {
        $unlike.on('click', function() {
            $.ajax('like.php', { data: 'here' }, function(response) {
                // do something with your response from like.php:
                $unlike.addClass("like");
                $unlike.removeClass("unlike");
                $like = $unlike;
            });
        });
    }
});

You will want to change { data: 'here' } to whatever data you want to send to like.php.

response will hold the data returned by like.php so make sure it is just a JSON result of the action IE:

echo json_encode(array('result' => '1'));

or

echo json_encode(array('result' => '2'));

you can then test if (response.result == 1) { var liked = true; } if (response.result == 1) { var liked = true; } in the callbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM