Assigning Ajax response to variable

Hello,

I am trying to assign an ajax response to a variable. How would I go about doing this?

$.ajax({
  url: 'http://crime.chicagotribune.com/api/1.0-beta3/crime/?format=jsonp&limit=500&community_area=10&crime_date_gte=2017-01-01',
  type: 'GET',
  dataType: 'json',
  async: false,
  success : function(data) {
    queriedData.push(data);
  }, error : function(req, err) {
    alert: ("Request:"+ JSON.stringify(req));
  }
  });

Any ideas?

You have the AJAX respone in the variable “data” in the example above? Have you console.logged(data) to see what you’ve received from the server?

1 Like

Hey, when you retrieve the information from the API.

Inside the function where it is suppose to parse those information, you can assign the return information there.

Because of the async nature the log returns null

You need to console.log(data) from within the scope of the success: callback. Does this make sense? Something like this:

$.ajax({
  url: 'whatever.com',
  type: 'GET',
  success: function(data){
    console.log(data) // this is your response obj that you can work with
  }
 });
function getJSON() {
  var resp = [];
 $.ajax({
  url: 'http://crime.chicagotribune.com/api/1.0-beta3/crime/?format=jsonp&limit=500&community_area=10&crime_date_gte=2017-01-01',
  type: 'GET',
  dataType: 'jsonp',
  async: false,
  success : function(data) {
    console.log(data);
    resp.push(data);
  }, error : function(req, err) {
      console.log(err);
  }
})
console.log(resp);
return resp;
}

This is what I’m trying but with no luck…

When you console.log(data) are you getting a response from the API?
You have a couple options with how you can proceed here if you are getting an API response.

To handle your async flow you can use callbacks, promises or generators etc. You could also just call another function inside your success block that does work with your api data. This is probably the simpliest option. Consider something like this.

function getJSON() {
  var resp = [];
  $.ajax({
    url: 'http://crime.chicagotribune.com/api/1.0-beta3/crime/?format=jsonp&limit=500&community_area=10&crime_date_gte=2017-01-01',
    type: 'GET',
    dataType: 'jsonp',
    success : function(data) {
      console.log(data);
      resp.push(data) //put it in an array if you really want to
      doSomethingWithArray(resp); //calling a function with your array
    }
  })
}

function doSomethingWithApiData(arr){
  console.log(arr) // do something with resp here
}

That’s probably the simplest option, but i’d still recommend learning to use callbacks, promises or generators — you can google and read about this stuff online. Hope this helps a bit.

1 Like

Promises and call backs aren’t needed. In a sense isn’t this a promise? Anyway, you commented, “put it in an array if you really want to.” I don’t. I’d rather have something like resp = data; but that just returned undefined. I don’t want to make it any more difficult than I need to pulling keys out of it later.

@Swoodend is right. You don’t want to do this. It’s a horrible idea, and you’re having a hard time getting it to work because it’s the worst way to work with AJAX requests. It’ll be easiest for you to use promises, which jQuery has made very convenient.

$.getJSON('https://url.com')
    .done(function(response) {
       // move all of your code in here and use the response object
       // many easy
       // wow
       // such simple
    })
1 Like

Okay,

var ajaxResp = $.ajax({
  url: "http://crime.chicagotribune.com/api/1.0-beta3/crime/?format=jsonp&limit=500&community_area=10&crime_date_gte=2017-01-01",
  dataType: "jsonp"
  })
.done(function() {
  console.log("success");
})
.fail(function() {
  console.log("error");
})
.always(function() {
  console.log('complete');
});

Pretty easy I have to say. It took me only a 20 minutes to figure out with jsonp vs the hours I spend yesterday. Now, I was wondering a thing or two. I have the whole thing assinged to ajaxResp.

How would I access the response and then iterate through the 500 objects for a specific value. The number one thing I have struggled with in my FCC journey is iterating through obejcts.

The obejct tree looks something like this

Object
   -done
   -always 
   -complete 
   -fail
   -progress 
   -responseJSON: Object
        -Meta: Object
        -objects: Array[500] 
             -object
             -object 
             -object 
                 -beat
                 -block
                 -case_number
                 -latitude 
                 -longitude

How would I be able to iterate through the response and pull out long lat and case number from each of the 500 objects and return something like this:

new google.maps.LatLng(37.782551, -122.445368),

but 500 of them…

Thank you!

You’re close. You’re done method gets passed the response data.

var ajaxResp = $.ajax({
  url: "http://crime.chicagotribune.com/api/1.0-beta3/crime/?format=jsonp&limit=500&community_area=10&crime_date_gte=2017-01-01",
  dataType: "jsonp"
  })
.done(function(response) { // <--- notice the argument here
  console.log(response); // <---- this will be the data you want to work with
})

response will probably be this part of what you were looking at

-objects: Array[500] 
             -object
             -object 
             -object 
                 -beat
                 -block
                 -case_number
                 -latitude 
                 -longitude

Since it’s an array, iterate through it with forEach

response.forEach(function(newsObject) { // <--- pass a function to forEach that takes a single object. This is called for every object in the array
  var lat = newsObject.someParameter.latitude;  // <--- I don't know what someParameter actually is.  You'll have to check it yourself
  var lng = newsObject.someParameter.longitude;
  var caseNumber = newsObject.someParameter.case_number;
}
1 Like

Thank you. I keep seeing other devs assign the whole thing to a variable. Why would they be doing this? Also, I apologize but edited my question. With the data I can spin out of it with forEach how can I create 500 new instances ofgoogle.maps.LatLng(lat, long) with that for each?

Again, thank you. You have been a huge help!

My example shows you how to get the latitude and longitude for the object. You’d just call that google.maps method in the forEach callback.

response.forEach(function(newsObject) { 
  var lat = newsObject.someParameter.latitude;  
  var lng = newsObject.someParameter.longitude;
  var caseNumber = newsObject.someParameter.case_number;
  google.maps.LatLng(lat, lng)
}
1 Like

Thank you!! I really appreciate your help!

1 Like