0

I'm trying to apply a CSS class to an element of my DOM HTML. Here's my HTML code : an i element inserted into a div.

<div class="delete delete_next"  data-url="{{call.url}}"  data-def="{{ call.person._id }}" data-annonce="{{ annonce._id }}"><i class="fa fa-check"></i></div>

In Javascript I'm doing an Ajax Query. if the json data.url I'm getting equals the url variable that I have in JS. I'm trying to add a css class to the element next to the div.

$('.delete_next').each(function(){

    var diff = $(this).data('def');
    var annonce = $(this).data('annonce');
    var url = $(this).data('url');

    $.ajax({
        url: 'index.php',
        data: {
            module: 'admin',
            action: 'call_url',
            diff: diff,
            ann: annonce
        },
        dataType : 'json',
        success : function(data){
            if(data.url == url){
                $(this).next().addClass('valdiate');
           }
        }
    })
});

And finally here's the CSS class :

<style>
    .valdiate{
        color: #327334;
        opacity: 1;
    }
</style>

So what's wrong in my code.

Thanks

KubiRoazhon
  • 1,759
  • 3
  • 22
  • 48

2 Answers2

1

You lose this context inside success handler

Use .bind(this)

OR

var _this=this; before ajax call and use $(_this).next().addClass('valdiate');

Try this:

$('.delete_next').each(function() {
  var diff = $(this).data('def');
  var annonce = $(this).data('annonce');
  var url = $(this).data('url');

  $.ajax({
    url: 'index.php',
    data: {
      module: 'admin',
      action: 'call_url',
      diff: diff,
      ann: annonce
    },
    dataType: 'json',
    success: function(data) {
      if (data.url == url) {
        $(this).next().addClass('valdiate');
      }
    }.bind(this)
  })
});

Edit: You can also use context in ajax settings, This object will be the context of all Ajax-related callbacks

Rayon
  • 36,219
  • 4
  • 49
  • 76
0

use this variable for current element

$('.delete_next').each(function(){
    var curelm = $(this);
    var diff = $(this).data('def');
    var annonce = $(this).data('annonce');
    var url = $(this).data('url');

    $.ajax({
        url: 'index.php',
        data: {
            module: 'admin',
            action: 'call_url',
            diff: diff,
            ann: annonce
        },
        dataType : 'json',
        success : function(data){
            if(data.url == url){
                curelm.next().addClass('valdiate');
           }
        }
    })
});
Sanjay Gohil
  • 144
  • 10