4

I am doing some ajax processing on click event that working fine but now I want to add class on success function I am using $(this).addClass("cover"); but nothing is happening . If I target class for add class mean if I use like this $('.dz-cover').addClass("cover"); it works fine but it add class all link tag that is with class name '.dz-cover' I don't want I just only want to add class only that link in which I am clicking. My code is below

$("#dropzonePreview").on("click", "a.dz-cover", function () {
    var id = $(this).data('id');
    $.ajax({
        type: 'POST',
        url: 'attachment/cover',
        data: {id: id},
        dataType: 'html',
        success: function (data) {
            $(this).addClass("cover");                   
        }
    });
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Muhammad Umar
  • 237
  • 2
  • 5
  • 20

3 Answers3

4

That is because context of element a.dz-cover is lost in ajax call, you can set context in ajax calls using option context:

$("#dropzonePreview").on("click", "a.dz-cover", function () {

var id = $(this).data('id');
$.ajax({
    type: 'POST',
    url: 'attachment/cover',
    context:this,
    data: {id: id},
    dataType: 'html',
    success: function (data) {
        $(this).addClass("cover");

    }
  });
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Not working. Now something strange is happening if i click one link class does not add on that link now i click on anther link now class is adding but not that in which click now it is adding on that link in which i click before – Muhammad Umar Mar 21 '16 at 09:06
  • @MuhammadUmar: you should show loader on click and then hide it in success function. – Milind Anantwar Mar 21 '16 at 09:42
2

this will not work in this case, because success is another block.

$("#dropzonePreview").on("click", "a.dz-cover", function () {
    var elm = $(this);
    var id = elm.data('id');
    $.ajax({
        type: 'POST',
        url: 'attachment/cover',
        data: { id: id },
        dataType: 'html',
        success: function (data) {
            elm.addClass("cover");
        }
    });
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

You are trying to use $(this) out of context. You should set it to a variable to be able to use it within your AJAX callback like so:

$("#dropzonePreview").on("click", "a.dz-cover", function () {
    var id = $(this).data('id');
    var element = $(this);
    $.ajax({
        type: 'POST',
        url: 'attachment/cover',
        data: {id: id},
        dataType: 'html',
        success: function (data) {
            element.addClass("cover");

        }
    });
});
toomanyredirects
  • 1,972
  • 15
  • 23