0

I am new to javascript. I want to store Json data in function getjsonData. I have Created a private function retrieveJsonData and I am passing it through getJsonData. but i can't access json outside onload function.

var DataController = (function(){
        var retrieveJsonData = function(){
            var api,ourRequest;
            api = 'http://52.69.49.40/assignment/getServiceData.php';
            ourRequest =  new XMLHttpRequest();
            ourRequest.open('GET',api);
            ourRequest.onload = function(){
                obj = JSON.parse(ourRequest.responseText);
                getJsonData(obj);
            }   
            ourRequest.send();
        }


        var getJsonData = function(object){
            return object;
        }

        return{
            AjaxObject:function(){
                getJsonData();
                console.log(getJsonData());
            }
        }


    })();
junaid
  • 57
  • 9

1 Answers1

1

Your getJsonData takes one parameter, and returns the value of that parameter. It is something called the "identity function", which does absolutely nothing. You probably want to store that data somewhere, which you can do by replacing your function with:

var data = undefined;
function getJsonData() {
  if (arguments.length > 0) {
    data = arguments[0];
  }
  return data;
}

It isn't a very good function, though, because it doesn't do what it says on the tin. It claims to get the JSON data, but it also stores it.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62