2
 $(document).ready(function () {
var user = 1;
 $("a.like").on("click", function () {
            var article = $(this).attr('data-article');
            $.ajax({
                type: "POST",
                url: "WebService.asmx/Like",
                data: "{ 'user': '" + user + "', 'article': '" + article + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if(msg.d ==  1)
                    {
                        $(".like[data-article='" + article + "']").fadeOut(700).addClass('unlike').removeClass('like').stop().text('Unlike').fadeIn(700);
                    }
                },
                failure: function (msg) {
                    alert(msg.d);
                }
            });
        });

$("a.unlike").on("click", function () {
            var article = $(this).attr('data-article');
            $.ajax({
                type: "POST",
                url: "WebService.asmx/Unlike",
                data: "{ 'user': '" + user + "', 'article': '" + article + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if(msg.d ==  1)
                    {
                        $(".unlike[data-article='" + article + "']").fadeOut(700).addClass('like').removeClass('unlike').stop().text('Like').fadeIn(700);
                    }

                },
                failure: function (msg) {
                    alert(msg.d);
                }
            });
        });
});

When I click on a link with class like it's working fine, the same when I click on a link with class unlike. However it doesn't working when I click the same link twice! When I'm searching on the internet, I see that I have to use live instead of click, however live was deprecated on 1.8 version. How can I make this fires multiple times?

samuk
  • 157
  • 1
  • 3
  • 19
  • RTFM: `live` is deprecated, and was replaced with `on`, your code doesn't work on a double click because 1) AJAX is async, and 2) You're not changing the class of your element, so you're always calling the same handler – Elias Van Ootegem Nov 05 '12 at 17:23
  • _live_ is useful if your DOM content changes, ie. you're loading more content through AJAX request and you want your old selectors to attach their events to the new data. If you just want to be able to call the same function twice, _live_ will not help you. – Halcyon Nov 05 '12 at 17:23
  • @FritsvanCampen - `live()` is not useful, it is as Elias is pointing out, in fact deprecated! – adeneo Nov 05 '12 at 17:29
  • @adeneo I would even go so far as to say `on` is not useful, but that's just me bashing the sizzle engine since it promotes a bad programming style. If `on` replaces `live` just read `live` as `on`. Carry live .. I mean, 'on'. – Halcyon Nov 05 '12 at 17:36

4 Answers4

10

Use jQuery.on():

$( document ).on( 'click', 'a.like', function () {
    // Do click stuff here
} );

http://api.jquery.com/on/

You need to bind on to an element that will always be present. (document or some main wrapper div). Using on with the dynamic element will not work.

Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
5

If you want to use on instead of live you need to write something like

$('#container').on('click', '.a.unlike', function () {

Since

$("a.like").on("click", function () {

Worked just as bind() did before it was deprecated.

If you want on() to act as live() you need to pass 3 arguments as in my first example.

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

Johan
  • 35,120
  • 54
  • 178
  • 293
1
$(document).on("click","a.unlike", function () {

is the live/delegated format of on.

http://api.jquery.com/live/

Sameera Thilakasiri
  • 9,452
  • 10
  • 51
  • 86
0

Before javascript can work after ajax call, you need to create new instance of your block of codes again e.g

<div class="clicks">
   //Ajax results comes here. For instance if we have sets of <a>Click me</a>, all we need to do is, when the call is successful we should construct our block of codes again because after document loads, javascript only read already existing elements.
</div>

var xhttp;
if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest();
} else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");`
        }

xhttp.onreadystatechange = function() {
    if(xhttp.readyState === 4 && xhttp.status === 200){
        $('.clicks').html(xhttp.responseText);
        //now re-create your functions here
        $('.clicks a').click(function(){
          alert('clicks worked after ajax call');
        });
    }
};
xhttp.open("GET","index.html",true);
xhttp.send(null);