Wikipedia API Not Returning JSON? [SOLVED]

Hello everyone,

I’ve just started the Wikipedia Viewer project. Although my code works if I replace the API request URL with the weather API I used in the previous challenge, I cannot get the JSON for the Wikipedia API to be displayed in the console. Any advice?

Here is a link to my project and my code:

$(document).ready(function(){
 accessWiki(); 
});

function accessWiki() {
  console.log("accessWiki is running");
  $.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=dog", function(data) {
    console.log(data);
  });
}

The console displays “accessWiki is running” but does not display the data object. Thanks!!!

If you open your browser console, you will see an error:

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=dog. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://s.codepen.io’ is therefore not allowed access.

You will have to use JSONP to fix it. It is as easy as adding &callback=? at the end of your url. If you have never heard of JSONP, google it or search this forum for an explanation.

3 Likes

Thank you so much! Adding “&callback=?” fixed this problem, and I will research JSONP to make sure I understand what is going on. Thanks!!

Hmm… my code was working fine yesterday. Today I was just trying to change from “onclick” to “onsubmit” for my button so that the enter key would also work, but now it seems that the API request is having trouble again… Any ideas of what I did wrong?

Thanks!!

Sorry, I fixed it. I forgot to remove the “submit” from my button’s type and was trying to use onsubmit and an event listener simultaneously… Yikes!

hi … according to wikipedia documentation , when we want data from outside of domain , eg. let we are at domain example.com and we want to retrive data from example.in , then these browse does not support cross domain data transfer , thats why you are not geting the response…

now wikipedia documentation suggested to use JSONP, ie we have to add callback parameter to our request, then wikipedia will return some data…
the request parameter wiill look like this:(https://en.wikipedia.org/w/api.php?action=opensearch&search=hello&callback=?",function(data)).

1 Like

You just saved the day for me with that bit of advice. I was having the same problem and your solution did the trick. Now on the finishing up this project.

I was also having the same JSON problem but adding the callback=? at the end of the url doesn’t work.

I never used to work with more horrible API than wikipedia ever