0

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);
                }
            });
        }
    });
Kevin Lu
  • 5
  • 1
  • 3
  • 1
    You can cache `$(this)` in another variable before doing the call, so `var image = $(this);` and then use `image` in the `success` function. – colinD May 05 '19 at 08:41

1 Answers1

-3

GET requests doesn't have data - which basically is the body of the requests. So for this solution the best is to provide API key inside URL like this:

https://pixabay.com/api/?key=${key}&q=${imageOf}&image_type=photo

Don't forgt to put this stirng into backticks (`) since it's interpolated string with variable key and imageOf

Then in response yo ucan go through just like their API documentation says: https://pixabay.com/api/docs/

pkolawa
  • 653
  • 6
  • 17
  • 1
    This has nothing to do with the question that was asked … and is completely wrong anyway. jQuery will encode the `data` property as the query string in a GET request, you don't need to do it manually. – Quentin May 05 '19 at 08:49