title: javascript - How to populate data on a select from XMLHttprequest
body: <p>Im trying to implement a vanilla javascript app that reads a JSON from a local server and with that JSON content I need to populate a select. The problem I have is that I´m trying to separate the code in 3 modules and my idea is to call the <strong>XMLHttprequest on the Model</strong> and <strong>set the json to a private Model variable(appData.categories)</strong>. And then <strong>use the data from the Model variable on the View to display it on a select</strong>.</p>
  
  <pre><code>var Model = (function () {
  
  var appData = {
      categories: []
  }
  
  function initCategories() {
      var xobj = new XMLHttpRequest();        
      xobj.overrideMimeType("application/json");
      xobj.open("GET", "/services/categories/", true); 
      xobj.onload = function () {
          if (xobj.readyState == 4 &amp;&amp; xobj.status == "200") {                
  
              appData.categories = JSON.parse(xobj.responseText);             
          }
      };
      xobj.send(null);
  }
  
  function getCategories() {
      return appData.categories;
  }
  
  return {
      initCategories: initCategories,
      getCategories: getCategories
  }
  })();
  </code></pre>
  
  <p>View</p>
  
  <pre><code>var View = (function () {    
  
  function displayData(total) {
      console.log(total);
  } 
  
  return {
      displayData: displayData
  }
  
  })();
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>var Controller = (function (modelCtrl, uiCtrl) { 
  
  function initCategories() {
      modelCtrl.initCategories(); // Call to async method
      var data = modelCtrl.getData(); // tries to get data 
      uiCtrl.displayData(data); // data is an empty array at this point
  }
  
  function init() {        
          initCategories();      
          console.log("app started");
  }
  
  return {
      init: init
  }
  
  })(ModelController, UIController);
  </code></pre>
  
  <p>Call to init function</p>
  
  <pre><code>Controller.init();
  </code></pre>
  
  <p>When i call the getCategories() method the variable is not populated yet, I can fill the select from inside the model the first time but I think there must be a better way. Thanks!</p>