Basically, I'm looping through an array of images. If the image doesn't have a source, it will make a ajax call to pixabay to find an image of the item and setting the URL to the src of the image element. However, calling "this" will reference the ajax call instead of the image element. My approach right now is to get the element's element ID from the "data" in the "options" but that isn't working. I also tried to call "imageOf" from inside the success callback but that doesn't work either.
$("img").each(function() {
if (!$(this).attr("src")) {
var imageOf = $(this).attr("imageOf");
//get imageURL via ajax call
var pixabayAPI = "https://pixabay.com/api/";
$.ajax(pixabayAPI, {
method: "GET",
async: false,
dataType: "json",
data: {
key: "...",
q: imageOf,
category: "food"
},
success: function(result, status, jqXHR) {
var images = result.hits;
if (images.length > 0){
console.log(images[0].webformatURL);
$(this).attr("src", images[0].webformatURL);
// "this" becomes the ajax call when I want to get the image element instead
};
},
error: function(e) {
console.log(e);
}
});
}
});