0

I am facing a problem with the following javascript function I created. It simply loops through all 'div.ajax' elements, fetches the URL from the data-url attribute, and should use the ajax call to load a new bunch of HTML which should be inserted into the element.

The problem is, I can't seem to be able to access the 'this' variable (containing the attribute) inside the request.done function (a scope issue). I tried to attach the 'this' variable to a global variable (document.this_element), but that doesn't work since sometimes multiple ajax calls are processed at the same time (hence the content is inserted into the wrong element).

I cannot use the .load() jquery function here, as I need some additional options only available to .ajax(). Does anyone know how I can solve this problem? Thanks!

//function to reload several blocks with ajax-injected data
function reload_ajax(){
   //foreach block
   $('div.ajax').each(function(index){

      //get url
      var url = $(this).attr('data-action');

      //make the block empty, add ajax loader image with CSS class
      $(this).addClass('not-loaded').html('');

      //make request
      var request = $.ajax({url: url, type: 'GET',data: {}, dataType: 'html'});

      //if request = done
      request.done(function(response){
         //SCOPE PROBLEM, 'this' element is not known
         $(this).removeClass('not-loaded').html(response);
      });

      //if request = failed
      request.fail(function(jqXHR, textstatus){
         //SCOPE PROBLEM, 'this' element is not known
         $(this).removeClass('not-loaded').html('<strong>Error:</strong> Could not load data.');
      });
   });
}
dirk
  • 2,206
  • 4
  • 21
  • 30
  • @Arun: the question you linked to does not solve my question. I have explained in my description that I tried exactly that approach, which doesn't work because several calls work simultaneously. The question you linked to doesn't have simultaneous ajax calls. – dirk Feb 26 '16 at 02:57
  • that doesn't matter.. because each call will have its own context... using a global variable won't solve the problem... – Arun P Johny Feb 26 '16 at 02:58
  • either use the `context` property, or use a closure variable within the each loop... `var self = this;` just before `var request = $.ajax({..})` then in the ajax handlers use `$(self)` instead of `this` – Arun P Johny Feb 26 '16 at 03:00
  • So yes, it is a duplicate.... – Arun P Johny Feb 26 '16 at 03:00
  • Sorry, you are correct. It works that way, thanks :) – dirk Feb 26 '16 at 03:03

0 Answers0