AJAX和JS for LIKE按钮

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&id="+(this).attr("id")",

is this syntactically correct if i'm sending two variables id and id1 ?

  data: "action=vote_up&id="+(this).attr("id")&id1="+(this).attr("id1")",

2) What goes into the href attribute? The php page or the AJAX?

<a href =""><img scr="like.png"></a>

3) which is run first.. The php page or the AJAX. 4) Is it mandatory for me to use jQuery or Pure Javascript for running AJAX

thanks for your time and patience. I most appreciate it.

<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.

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 )

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:

<a class="like" href="handle_vote.php?action=vote_up&id=<?php echo $post_id; ?>"><img src="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.