0

I am playing with grabbing media from the Instagram JSON with jQuery. I want to access the two most media. So in their JSON media array it would be [0] and [1]. But I encountered the following problem:

 $.getJSON(`https://www.instagram.com/${handle0}/?__a=1`, function (data) {
        var content = data.user.media.nodes;

        for (var i = 0; i < 2; i++) {
            var code = content[i].code;
            var igUrl = `https://www.instagram.com/p/${code}`;
            var contentUrl = '';

            console.log("here", i)

            if (content[i].is_video === true) {
                $.getJSON(`https://www.instagram.com/p/${code}/?__a=1`, function (data) {

                    console.log("video", i)

                    contentUrl = data.graphql.shortcode_media.video_url;
                    $('#content' + i).attr('href', igUrl).append(`<video autoplay loop muted><source src = ${contentUrl} type="video/mp4" ></video>`)
                })
            } else {
                contentUrl = content[i].thumbnail_src;

                console.log("image", i)

                $('#content' + i).attr('href', igUrl).append(`<img src = ${contentUrl}>`)
            }
        }
    })

My console.log("video", i) returns a 2 every time, even though my for loop specified for i to not be greater than 2.

My console.log("here", i) logs 0, 1, and if the image is an image my console.log("image", i) also logs correctly.

Please let me know if this question is confusing.

aydinugur
  • 1,208
  • 2
  • 14
  • 21
Kaisin Li
  • 514
  • 3
  • 7
  • 21
  • 2
    The for loop is inside the callback of an AJAX request and in it, new AJAX requests are created, each with its on callback. `console.log("video", i)` is executed in this nested callback. By the time the nested callbacks are executed, the for loop has long ended and the variable `i` is at its last value. – marekful Nov 09 '17 at 06:16
  • `for (let i = 0; i < 2; i++) {` – dandavis Nov 09 '17 at 06:55

0 Answers0