Home > Back-end >  Array issue in JS
Array issue in JS

Time:11-24

I ran into an issue where I can't figure out how to pull the data from a TPA API. Would greatly appreciate any help!:) This is the link to the API: https://www.themealdb.com/api/json/v1/1/random.php

I'm trying to pull out the name of the meal, instructions picture, and the source of the recipe, using an ajax method.

This is the basic structure I have right now:

let randomGenerator = function(){
    $.ajax({
        method: "GET",
        url: "https://www.themealdb.com/api/json/v1/1/random.php",
        success: function(r){
            console.log(r);
        let meals = r["meals"]
        let pic = meals[34]
        let name = meals[23]
        let instructions = meals[29]
        let source = meals[52]
        $("#random-name").html(name)
        $("#random-description").html(instructions)
        $("#random-source").html(source)
        $("#random-photo").attr("src", pic)
        },
        error: function(data){
          console.log(data);
        }
  });
  
  }

This is the result from the API when fetched from above link:

{
  "meals": [
    {
      "idMeal": "52964",
      "strMeal": "Smoked Haddock Kedgeree",
      "strDrinkAlternate": null,
      "strCategory": "Breakfast",
      "strArea": "Indian",
      "strInstructions": "Melt 50g butter in a large saucepan (about 20cm across), add 1 finely chopped medium onion and cook gently over a medium heat for 5 minutes, until softened but not browned.\r\n\r\nStir in 3 split cardamom pods, \u00bc tsp turmeric, 1 small cinnamon stick and 2 bay leaves, then cook for 1 minute.\r\n\r\nTip in 450g basmati rice and stir until it is all well coated in the spicy butter.\r\n\r\nPour in 1 litre chicken or fish stock, add \u00bd teaspoon salt and bring to the boil, stir once to release any rice from the bottom of the pan. Cover with a close-fitting lid, reduce the heat to low and leave to cook very gently for 12 minutes.\r\n\r\nMeanwhile, bring some water to the boil in a large shallow pan. Add 750g un-dyed smoked haddock fillet and simmer for 4 minutes, until the fish is just cooked. Lift it out onto a plate and leave until cool enough to handle.\r\n\r\nHard-boil 3 eggs for 8 minutes.\r\n\r\nFlake the fish, discarding any skin and bones. Drain the eggs, cool slightly, then peel and chop.\u2028\r\n\r\nUncover the rice and remove the bay leaves, cinnamon stick and cardamom pods if you wish to. Gently fork in the fish and the chopped eggs, cover again and return to the heat for 2-3 minutes, or until the fish has heated through.\r\n\r\nGently stir in almost all the 3 tbsp chopped fresh parsley, and season with a little salt and black pepper to taste. Serve scattered with the remaining parsley and garnished with 1 lemon, cut into wedges.",
      "strMealThumb": "https:\/\/www.themealdb.com\/images\/media\/meals\/1550441275.jpg",
      "strTags": "Brunch,Fish,Fusion",
      "strYoutube": "https:\/\/www.youtube.com\/watch?v=QqdzDCWS4gQ",
      "strIngredient1": "Butter",
      "strIngredient2": "Onion",
      "strIngredient3": "Cardamom",
      "strIngredient4": "Turmeric",
      "strIngredient5": "Cinnamon Stick",
      "strIngredient6": "Bay Leaf",
      "strIngredient7": "Basmati Rice",
      "strIngredient8": "Chicken Stock",
      "strIngredient9": "Smoked Haddock",
      "strIngredient10": "Eggs",
      "strIngredient11": "Parsley",
      "strIngredient12": "Lemon",
      "strIngredient13": "",
      "strIngredient14": "",
      "strIngredient15": "",
      "strIngredient16": "",
      "strIngredient17": "",
      "strIngredient18": "",
      "strIngredient19": "",
      "strIngredient20": "",
      "strMeasure1": "50g",
      "strMeasure2": "1 chopped",
      "strMeasure3": "3 Pods",
      "strMeasure4": "1\/4 tsp",
      "strMeasure5": "1 small",
      "strMeasure6": "Sprigs of fresh",
      "strMeasure7": "450g",
      "strMeasure8": "1 Litre",
      "strMeasure9": "750g",
      "strMeasure10": "3",
      "strMeasure11": "3 tblsp chopped",
      "strMeasure12": "1 chopped",
      "strMeasure13": " ",
      "strMeasure14": " ",
      "strMeasure15": " ",
      "strMeasure16": " ",
      "strMeasure17": " ",
      "strMeasure18": " ",
      "strMeasure19": " ",
      "strMeasure20": " ",
      "strSource": "https:\/\/www.bbcgoodfood.com\/recipes\/2256\/smoked-haddock-kedgeree",
      "strImageSource": null,
      "strCreativeCommonsConfirmed": null,
      "dateModified": null
    }
  ]
}

I keep getting undefined as the array has only one object -> 0, that one random meal, so I'm very confused about how to pull that info out. I created a button that should generate these things on the page, hence the HTML inside.

CodePudding user response:

The return has an array of meals, so just access meals[0].whatever_var_you_want

eg.

$.ajax({
  method: "GET",
  url: "https://www.themealdb.com/api/json/v1/1/random.php",
  success: function(r){
    var meal = r.meals[0];
    $("#random-name").html(meal.strMeal)
    $("#random-description").html(meal.strInstructions);
    $("#random-source").html(meal.strSource)
    $("#random-photo").attr("src", meal.strMealThumb)
  },
  error: function(data){
    console.log(data);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p id="random-name"></p>
<p id="random-description"></p>
<p id="random-source"></p>
<img id="random-photo"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Per www.themealdb.com:

Lookup a single random meal www.themealdb.com/api/json/v1/1/random.php

Lookup a selection of 10 random meals (only available to $2 Patreon supporters) www.themealdb.com/api/json/v1/1/randomselection.php

So it is expected to have only one object in the array. To have multiple random selections you have to subscribe. And probably your code would look a bit like:

$.ajax({
    method: "GET",
    url: "https://www.themealdb.com/api/json/v1/1/randomselection.php", //needs subscription
    success: function(r){
    for (let i=0; i<r["meals"].length; i  ) { let meal = r["meals"][i].idMeal; let name=r["meals"][i].strMeal; // ... } }
    },
    error: function(data){
      console.log(data);
    }
});

CodePudding user response:

You should be able to access the meal using the syntax r["meals"][0].

Once you have the meal object, you can get the image, name, instructions and source using strMealThumb, strName, strInstructions and strSource respectively.

$.ajax({
    method: "GET",
    url: "https://www.themealdb.com/api/json/v1/1/random.php",
    success: function(r) {
        let meal = r["meals"][0];
        let pic = meal.strMealThumb;
        let name = meal.strMeal;
        let instructions = meal.strInstructions;
        let source = meal.strSource
        $("#random-name").html(name)
        $("#random-description").html(instructions)
        $("#random-source").html(source)
        $("#random-photo").attr("src", pic)
    },
    error: function(data){
      console.log(data);
    }
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP u1T9qYdvdihz0PPSiiqn/ /3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<img id="random-photo" width="80px"/><br>
<b>Name:</b><p id="random-name"></p>
<b>Source:</b><p id="random-source"></p>
<b>Instructions:</b><p id="random-description"></p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related