Bismo Funyuns
Bismo Funyuns

Reputation: 73

Ajax query for JSON data not returning data

I'm trying to use World Bank's API to obtain some data. This is how to query their database. Basically to query a country's information, I would need to go to this url:

http://api.worldbank.org/countries/"alpha2Code of the country"

In my code here (Link to CodePen code.) I use use the alpha2Code from a previous query to add to the World Bank query's URL. Here's the method:

getDetails(alpha2Code) {
  this.load('http://api.worldbank.org/countries/'+alpha2Code)
    .then((countryDetails) => {
      this.generateOverlay(countryDetails);
    });
},

the load() method is defined here:

load(url, type = 'json') {
  return $.ajax({
    dataType: type,
    url: url,
  });
},

According to World Bank's basic calling format, I would need to add

format=json

in order to receive response in JSON. Somehow I don't think it's actually obtaining anything from WorldBank.

The query to World Bank is suppose to give me details to put into the overlay that covers the country flags after a click.

Thank you in advance for the help!

Upvotes: 1

Views: 128

Answers (2)

gpanders
gpanders

Reputation: 1421

One issue with the CodePen you shared that may or may not be the problem with your site is that the CodePen demo is loaded over HTTPS, but you're requesting an insecure resource (HTTP). Browsers don't like this and will usually block it.

Unfortunately, you can't just change the request to be HTTPS since the WorldBank API doesn't have its certificates sorted out, so those requests are blocked by the browser as well. One solution would be to load your site over HTTP; however, this is obviously not advisable if your page contains any user-sensitive information.

The better way is to use your own back-end server as a proxy. You can setup your own API on your server that queries the WorldBank API over HTTP and can then respond to your request over HTTPS. Of course, this assumes you have control over your backend which is not always the case.

Upvotes: 1

Cyrus
Cyrus

Reputation: 46

You need to pass the desired result format in the query. For example, to query INDIA, you would need to change the url to :

http://api.worldbank.org/countries/IN?format=json

The resulting data received is like:

[{"page":1,"pages":1,"per_page":"50","total":1},[{"id":"IND","iso2Code":"IN","name":"India","region":{"id":"SAS","value":"South Asia"},"adminregion":{"id":"SAS","value":"South Asia"},"incomeLevel":{"id":"LMC","value":"Lower middle income"},"lendingType":{"id":"IBD","value":"IBRD"},"capitalCity":"New Delhi","longitude":"77.225","latitude":"28.6353"}]]

The default output is in XML format. Hence your code may not be working.

Upvotes: 0

Related Questions