0

I have a JSON array like:

[  
  {  
     "location":"New York",
     "company":"XYZ LTD",
     "status":"Active"
  },
  ... etc
]

I am using the following function to return this array from a URL:

var getJSON = function(url, successHandler, errorHandler) {
  var xhr = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
    : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('get', url, true);
  xhr.onreadystatechange = function() {
    var status;
    var data;
    // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
    if (xhr.readyState == 4) { // `DONE`
      status = xhr.status;
      if (status == 200) {
        data = JSON.parse(xhr.responseText);
        successHandler && successHandler(data);
      } else {
        errorHandler && errorHandler(status);
      }
    }
  };
  xhr.send();
};

We use the function like this:

getJSON('http://example.com/json.php', function(data) { 
  alert('Data was collected successfully.');
}, 
function(status) { 
  alert('Something went wrong while retrieving the location data.');
});

Okay so great this works and the 'data was collected. I am quite new to Javascript and I am unsure of how I would store the data that was collected as a a variable in Javascript.

I have tried:

getJSON('http://example.com/json.php', function(data) { 
  var myData = data;
}, 
...end

And:

var myData = getJSON('http://example.com/json.php', function(data) { 
  return data;
}, 
...end

But at this point, if I do:

console.log(myData);

Then I get undefined. But if I do:

var myData = getJSON('http://example.com/json.php', function(data) { 
  console.log(data);
}, 
...end

I get back [Object,Object] and this is my data!.

So how do I get my data out of the successHandler and stored as a variable?

1 Answer 1

1
var myData;
getJSON('http://example.com/json.php', function(data) { 
  myData = data;
}, ...

declaring the variable outside the function scope. that's the trick.

best regards.


Update: Pls notice, that ajax is asyncron. if you make the console output right under the getJSON Call it won't work, because the data isn't received yet.

Sign up to request clarification or add additional context in comments.

3 Comments

Hello and thanks for the input! I was just going to say that I still get undefined but then I realized already that this could be the case. I guess the usage that I have for this would be better suited to a synchronous version of this function? Off topic but how would you do that... Get it to log the object to the console but only after it had been received? Promises?
you can change xhr.open('get', url, true); to xhr.open('get', url, false); (now it's syncronous). but I won't do that because in this case the browser freeze till the response of your request is availible. normaly you don't want that. in javascript you have to learn to code with callbacks. all parts of javascript are build with callbacks (eventhandler, ajax, services, and so on). if you want to talk about it, I can help you with your question. But pls not here. open a chat on stackexchange and invite me.
I think that you have a good point. I have experience with PHP so I have to change my mind set here. What I am trying to do is read this data into JS to use as a source for map marker positions in google maps, I think I need to make this synchronous but I am really not sure, if you would so kindly provide some further feedback on this then that would be great! Have created a room and invited you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.