Search code examples
javascriptajaxiife

AJAX call using IIFE? Can't seem to get .done to work the same as a regular function


I currently have an AJAX call out to a PHP file that works, that is the following:

//Load map from database
function getMap(){
    return $.ajax({
    url: "getMap.php",
    type: "POST",
    dataType: 'JSON',
    });
};
getMap().done(function(r) {
    if (r) {
        loadedMap(JSON.parse(r.mapArray), JSON.parse(r.mapProperties)); //call     loadedMap(r) if loading a map from DB
    } else {
       console.log("No data");
    }
}).fail(function(x) {
   console.log("error");
});

That works within a single javascript file that successfully passes r.mapArray and r.mapProperties to my main loadedMap function.

I'm trying to learn about the IIFE Javascript Module model, and split my work up into separate files.

So, I currently have main.js:

(function() {
  // let's get our map
  var gameMap = mapGen.getMap().done();
  console.log(gameMap);
})();

and mapGen.js:

var mapGen = function() {  
   return {
      getMap: function() {
        return $.ajax({
            url: "getMap.php",
            type: "POST",
            dataType: 'JSON',
        });
      }
   };
}()

If I console.log(gameMap), I see the responseText JSON object with my data. I just can't seem to access it. console.log(gameMap.responseText) is undefined. as is gameMap.responseJSON (though I see both of them in the console).


Solution

  • Looking the code over it looks as the the separation of the files was not the issue and that looks to be implemented correctly. The issue is with how you are handling the AJAX request. The function mapGen.getMap() actually returns a jqXHR Object as opposed to the response that you are trying to access.

    Just as you had in your previous file, you will need handle the response of your request.

    (function() {
      // let's get our map request
      var gameMap = mapGen.getMap();
      gameMap.done(function(r){ ... }).
      fail(function(x){ ... });
    })();
    

    You will be able to access the response data you are looking for within the done() function.