0

In my code below, I am looping over each anchor link, getting the text value, firing it over ajax and getting a json response back. Its all working fine.

However, in the last stage of success, I am trying to add the response as a class to the anchor I am currently looping over with $(this)

$( ".field-name-field-staff .field-item a" ).each(function() {
      var username = $(this).text();
      var date = $(this).closest('td.views-field-field-event-date').find('span.date-display-single').text();
      $.ajax({
          type: 'GET',
          url: "bookings/availability/data",
          data: {
              "username": username,
              "date" : date
          },
          success: function (data) {
            console.log(data);
            console.log(data.css);
            console.log(this);
            $(this).addClass(data.css); 
          }
        });
    });

In the example above, In the console.logs, I get...

  • An array of all data (works)
  • A single value from that array (works)
  • A full array dump of the ajax request object (NOT the anchor tag i want)

Can someone tell me how i go outside of the ajax and get the anchor object outside it?

Collins
  • 1,069
  • 14
  • 35
  • 1
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – freedomn-m Feb 27 '18 at 11:18
  • Related link will give more info - but to fix this you need to store 'this' outside the ajax request and then use it inside, eg `$("..").each(function() { var el = this; ... $.ajax({ .. success: function (data) { console.log(el); el.addClass(data.css); } ...` – freedomn-m Feb 27 '18 at 11:20

1 Answers1

2

$(this) inside the ajax is pointing to the this of ajax success function. You need to collect the this object to keep its pointer aligned with the parent.

Here to achieve this try below

$(".field-name-field-staff .field-item a").each(function() {
  var self = $(this);
  var username = self.text();
  var date = self.closest('td.views-field-field-event-date').find('span.date-display-single').text();
  $.ajax({
    type: 'GET',
    url: "bookings/availability/data",
    data: {
      "username": username,
      "date": date
    },
    success: function(data) {
      console.log(data);
      console.log(data.css);
      console.log(this);
      self.addClass(data.css);
    }
  });
});
Anand G
  • 3,130
  • 1
  • 22
  • 28