Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Problem with receiving the data from json callback from Wikipedia's API

Hello,

So using other learn-to-code site and after the video course on AJAX here on Teamtreehouse i tried to make use of wiki's api.

My wiki article viewer should get 10 articles about the typed word from wiki's database and show it on the page.

Do i have a bug in the code in the ajax part? Here's the part that happens when the query button is clicked:

  $("#search-icon").mouseup().mousedown(
    // AJAX 
    function getArticles() {
      if (value !== "" || value !== undefined) {
      mainLink = "https://en.wikipedia.org/w/api.php?action=query&format=json&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts|pageimages&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max" + "&gsrsearch=" + value + "&callback=?";
         console.log(mainLink);
        $.getJSON(mainLink, function (response) {
            articlesList = "<ul>";
          $.each(response.query.pages, function(index, article){

           if (index===2) {
              articlesList += "<li>" + "<h3>" + article.title + "</h3>";
           }

            if (index===4) {
              articlesList += "<p>" + article.extract +"</p>" + "</li>";
            }
          });
          articlesList += "</ul>";
        });

        $("#mainsection").html(articlesList);
      }

    }
  ); ```

2 Answers

Your main problem is that the response you get from the wikipedia-url is not valid JSON. If you look at the response, you'll need to remove '/**/(' from the start of the string, and ')' from the end.

You can test the result here

Here is also an example (in plain javascript though, but this works):

function httpGetAsync(theUrl, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

var url = 'https://en.wikipedia.org/w/api.php?action=query&format=json&generator=search&gsrnamespace=0&gsrlimit=10&prop=extracts|pageimages&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max%22%20+%20%22&gsrsearch=%22%20+%20value%20+%20%22&callback=?%22';

httpGetAsync(url, function (response) {
    var result = response.replace('/**/"(', '');
    result = result.replace('}})', '}}');

    console.log(JSON.parse(result));
});

I changed the url. But now when i have pure JSON it doesn't work either. What i see in the console now is cross-origin fail message, but why if I use jsonp, and can see the file when i click the url anyway?

" XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&generator=searc…laintext&exsentences=1&exlimit=max&callback=JSON_CALLBACK&gsrsearch=Warsaw. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access. "

I know that when i have '&format=json' and a callback in the url - it's jsonp, right? So why wasn't i allowed access?

Sorry! This is a very late response but hopefully it can help others with the same problem.

To get the JSON data to come through, you need to add the origin parameter to your URL. Just append &origin=* to the end of your request URL and it should come through fine. I go into more detail about this in some instructions that I wrote up regarding this issue.