-2

I have the following code and I want to access the json of the outside of the initial call.

var crimes = $.getJSON('url');

console.log(crimes);

the console logs an object with a "responseJSON" element, but I can't access it. The code:

console.log(crimes[responseJSON]);

returns an error saying respponseJSON is undefined. I need to cycle through this large dataset in another for look so I only want to call it once rather than every time in the loop that comes after. How do I access the responseJSON object?

user2907249
  • 839
  • 7
  • 14
  • 32
  • Try crimes.responseJSON. If that also gives an undefined error then most likely it is actually a string and not an object so you need to deserialize it to an object. – nurdyguy May 06 '16 at 20:15
  • 2
    `$.getJSON` is asynchronous. Please read the documentation: https://api.jquery.com/jQuery.getJSON/ – Felix Kling May 06 '16 at 20:18
  • That doesn't really help me understand how to access the JSON outside the initial $.getJSON() call. – user2907249 May 06 '16 at 20:28
  • http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello May 06 '16 at 20:28
  • Not sure what you mean by "outside the initial $.getJSON() call". What does "outside" mean here? How would "inside" look like? – Felix Kling May 06 '16 at 20:30

1 Answers1

2

$.getJSON returns a jqXHR object, and while it may have a responseJSON property, you cannot access it this way (or at that moment). You have to "wait" until the browser performed the Ajax request. You do this by passing a callback to $.getJSON, which gets called when the response is available.

From the jQuery documentation (adapted):

$.getJSON( "ajax/test.json", function( data ) {
  // access data here
});

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method.

It seems you are not familiar with Ajax, so you should definitely read the jQuery tutorial about Ajax.

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

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143