Search code examples
javascriptjsonxmlhttprequest

getting JSON data from REST API by JavaScript displays partial data


I am trying to get data from alchemynewsapi through JavaScript. The sample data I receive is:

{
"status": "OK",
"totalTransactions": "68",
"result": {
    "docs": [
        {
            "id": "ODU1MjM4MjM0NnwxNDQ5MDk0Mzgy",
            "source": {
                "enriched": {
                    "url": {
                        "title": "North Scituate observatory hosts workshop on telescopes",
                        "url": "http://www.providencejournal.com/article/20151201/entertainmentlife/151209982"
                    }
                }
            },
        {
            "id": "ODEzMzYxODU5MHwxNDQ5MDYyMjM0",
            "source": {
                "enriched": {
                    "url": {
                        "title": "Mob Programming Workshop",
                        "url": "https://www.eventbrite.com/e/mob-programming-workshop-tickets-19710798529"
                    }
                }
            },
            "timestamp": 1449062234
        }
    ],
    "next": "MzY5OTc0NjQzNzI2MjMxNzM2N3xPREU1TnpnNU9EWXhPSHd4TkRRNU1EWTNPVFE1",
    "status": "OK"
   }
}

I am trying the following for retrieving title and URL fields of the data:

var jsonData=getJSON('http://urlofapi').then(function(data) {
for(var i=0; i<data.result.docs.length; i++)
 {
     result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
 }
}, function(status) { //error detection....
alert('Something went wrong.');
});

getJSON is a function I have created :

var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status == 200) {
    resolve(xhr.response);
  } else {
    reject(status);
  }
};
xhr.send();
});
};

But it only displays me the last title of the data i.e here the "Mob..."

What needs to be done to retrieve all the titles if there are 100's of items?


Solution

  • It's quite normal, your code has:

    result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
    

    Which means you constantly replace the contents of resultwith a new title, so at the end, you display the last one.

    You need to concatenate the data somehow, or use console.log if you're just trying to see the results before doing something more with them.