1

I've been struggling with getting the data out of an AJAX call using jQuery. I'm using RequireJS so my JavaScript can be more maintainable/modular. I've only been using RequireJS for a few days, so I may or may not be doing this right. Just looking for a way to keep my JS modular and clean.

Here is what I have so far. I know for a fact that it's getting the correct data because if I console.log(data[Math.floor(Math.random()*data.length)]), the data is there. The JSON file is long so I won't show you that, just take my word for it — it works.

var maze;
define(["jquery"], function($){
    $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            var maze = data[Math.floor(Math.random()*data.length)];
        }
    });
    return {
        randomMaze: maze    
    };
});

I also tried this (declaring maze within anonymous function)

define(["jquery"], function($){
    var maze;
    $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            var maze = data[Math.floor(Math.random()*data.length)];
        }
    });
    return {
        randomMaze: maze    
    };
});

I don't know what I'm doing wrong. Just trying to return data[Math.floor(Math.random()*data.length)]

Matthew
  • 2,158
  • 7
  • 30
  • 52
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – kryger Aug 11 '15 at 07:22

1 Answers1

1

jQuery.ajax() success returns results asynchronously , maze may not be defined when called synchronously outside of success at

return {
        randomMaze: maze    
    };

Try returning jQuery promise object $.ajax() from function , returning object within asynchronous success callback

 // return jQuery promise object
 return $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            // return object as jQuery promise value
            return {
                     randomMaze: data[Math.floor(Math.random()*data.length)];
            }
        }
    });

See also How do I return the response from an asynchronous call?

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177