0

Ok, so I'm having a problem with my $.getJSON functions.

I'm running a for loop containing a get json function but the variable 'i' which is used in the for loop is equal to 2 when the json function runs.

This causes the function to target the wrong element.

I think this is happening because the json function is a-synchronized and the for loop continues on and ends when 'i' hits 2.

The rest of the code works fine I just need to know if I can make the json function synchronized

I really don't know how to fix the problem and I'd prefer to not use ajax functions as I'm not familiar with them yet although I do know that they can be synchronized.

Here's the Javascript...


  $.getJSON( "Scripts/Homepage.json", function( data ) {

    for (var i = 0; i < 2; i++) {

      $($(".recipe").get(i)).attr("data-recipe", data.Recipes[i]);

      let recipe = $($(".recipe").get(i)).attr("data-recipe");

      $.getJSON( "Posts/" + recipe + ".json", function( data ) {

        $($(".recipe").get(i)).css({
          background: "url('" + data.Images[0] + "')",
          backgroundSize: "cover",
          backgroundRepeat: "no-repeat"
        });
      });
    }
  }
Procode238
  • 43
  • 7
  • Have a look at: [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – 3limin4t0r May 25 '19 at 12:45

1 Answers1

0

I don't think that there is a solution to my problem without ajax so I decided to go back and use an ajax function instead.

Procode238
  • 43
  • 7