Eutherpy
Eutherpy

Reputation: 4571

Javascript error parsing http response

I am trying to parse the response from the www.skiddle.com API in Javascript:

$.ajax({
        url: 'http://www.skiddle.com/api/v1/events/search/?api_key=myapikey' + '&latitude=' + lat + '&longitude=' + long + '&radius=800&eventcode=LIVE&order=distance&description=1',
        type: "GET",
        success: function(response) {
        var list = [];
        $(response).find("results").each(function() {
        var el = $(this);
        var obj = {
                   "eventname": el.find("eventname").text(),
                   "imageurl" : el.find("imageurl").text(),
                  };
        list.push(obj);
        });

The response actually has a results property with one element in the array:

{error: 0, totalcount: "1", pagecount: 1, results: Array(1)}

but I can't seem to parse it correctly, $(response).find("results") returns nothing.

Upvotes: 0

Views: 362

Answers (2)

AvcS
AvcS

Reputation: 2323

The response you are getting is a JSON, you are trying to parse it as XML.

The list you are trying to get can be obtained by simply using

success: function(response) {
    var list = (response.results || []).map(function(result) {
        return {  
            eventname: result.eventname,
            imageurl : result.imageurl
        };
    });
}

Upvotes: 0

Shyju
Shyju

Reputation: 218732

If you are sure that there will be a result array property in your response, you may simply use response.results which gives you the array.

success: function(response) {

  $.each(response.results,function(indx,item){
       console.log(item);
       var obj = {  
                    eventname: item.eventname,
                    imageurl : item.imageurl
                 };
      list.push(obj);
  });

}

Assuming list is an array defined earlier.

Also if you are sure there will be only one item in the array, you do not need a loop, you can access it via response.results[0]

success: function(response) {
  if (response.results.length>0) {
     var obj = { eventName: response.results[0].eventname,
                 imageurl : response.results[0].imageurl };
     list.push(obj);
  }
}

I also noticed that the your new object has the same property names as the object you are iterating. In that case, you can simply add the same object

 list.push(response.results[0]);

Of course this will add the first item as it is , which means if that has additional properties (other than eventname and imageurl) those will be present in the item you are adding to list now..

Upvotes: 2

Related Questions