0

I am trying to return a json array to a function and output the results. Here is a sample of what I want to achieve but 'thisArray' keeps coming up as 'undefined'. What am I doing wrong? Grateful for feedback...

<html>
<head>
<title>Test Array</title>

function recipesTestObject(recId, recipe)
{
 this.recId = recId;
 this.recipe = recipe;

}

function initialise() {


    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", { recCategory: 2 }, function(json) {
         var recipeTest = new Array();
        $.each (json.recipes, function (){

         recipeTest[recipeTest.length] = new recipesTestObject(this['id'], this['recName']);


        });

     return recipeTest; 

    });


   }

    function display(thisArray) {

for (var i=0; i < thisArray.length; i++) {
    document.write("Name: "+thisArray[i].recipe+"<br>");

}

    }
   </script>
   </head>
<body>
<script language="javascript">

var x;

x = initialise();

display(x);
</script>
</body>
</html>
  • In addition to the duplicate, once you fix the async issue, you'll find that you shouldn't be using `document.write()` because it will be invoked after the page has loaded. – cookie monster Jan 17 '14 at 00:18

2 Answers2

0

You're returning it inside the success callback function, but not from the initialise function.

There are many ways around this, one is to use callbacks:

function initialise(callback) {

    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", 
    { recCategory: 2 }, function(json) {
        var recipeTest = [];
        $.each (json.recipes, function (){
            recipeTest.push(new recipesTestObject(this['id'], this['recName']));
        });
    callback(recipeTest);
    });
}

And then you call it like this:

initialise(display);
Shomz
  • 37,421
  • 4
  • 57
  • 85
0

thisArray is undefined because initialise doesn't return a value.

You can fix this by using a callback function:

function initialise(callback) {
    $.getJSON("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", {
        recCategory: 2
    }, function (json) {
        var recipeTest = [];
        $.each(json.recipes, function () {
            recipeTest.push(new recipesTestObject(this.id, this.recName));
        });
        callback(recipeTest);
    });
}

And then instead of

var x;
x = initialise();
display(x);

you can do this:

initialize(display);

Notice that I used [] instead of new Array(). This is the preferred way to initialize arrays.

I also used recipeTest.push(...) instead of recipeTest[recipeTest.length] = ... since push is the preferred method of adding an item to an array.

You can also do this.id instead of this['id'].

Peter Olson
  • 139,199
  • 49
  • 202
  • 242