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.');
});
});
}