Skip to content Skip to sidebar Skip to footer

Ajax And Js For Like Button

I'm trying to learn how make an AJAX script for a LIKE button, on my website. I have the following questions: if i'm sending 1 variable.... id.. I do this data: 'action=vote_up&am

Solution 1:

1) Yes, you could simple undestand it as a PHP-Get request to a script, so multiple vars are possible, like Adam mentioned.

2) For backwards compatibility you should just link to a PHP/whatever-Script that provides the same functionality but doesn't rely on javascript (Not everyone has js enabled). In your javascript you just disable the defult click actione ( see: http://api.jquery.com/event.preventDefault/ ) otherwise it you only want to allow the like funktionality if js is enabled than you could just link to the page anchor '#'.

3) The page runs first. It is progressed by the server and than sent to your browser. In the browser the recieved javascript will start its action.

4) Everything you are using in jquery is based on simple javascript functions, but jquery is much more comfortable ;) The equivalent to the ajax method of jquery is XMLHttpRequest ( http://www.w3schools.com/xml/xml_http.asp )

Solution 2:

Here is a idea, hope it helps.

If handle_vote.php is the URL responsible for the handle the up vote, you must do two things:

  1. the a href is the URL with the query string for the up vote, your data, is this case. It must be generated for you server application. It will be used in case of no javascript.

  2. you should put you event to handle the up vote in the a onclick event, to send the ajax request, and use the preventDefault jQuery function to avoid the default event. In this case, a href will never be used, the js will suppress the link click.

A code sample will be almost like this, in you php page:

<aclass="like"href="handle_vote.php?action=vote_up&id=<?phpecho$post_id; ?>"><imgsrc="like.png"></a>

And it as your jQuery script:

$(function() {
    $('a.like').on('click', function(e) {
        e.preventDefault();
        $.get($(this).attr("href"));
    });
});

You can personalize as you like, it is only the idea of how to do it.

Solution 3:

<a href ="#"><img scr="like.png"></a> put onclick event on that link, and make AJAX request` to increment count, on success response update count clicks on button. And you forgot about one thing, you should save the state of that button. Because one user can go to your site and click 1000 times on it.

Post a Comment for "Ajax And Js For Like Button"