Using Wikipedia's API to fetch results from search query

victoria picture victoria · May 2, 2016 · Viewed 13.1k times · Source

I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :

 "use strict";
$(document).ready(function(){

function searchWikipedia(searchCriteria){
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);

}


$('#btn').click(function searchCriteria() {
    var searchCriteria = $("input[name=Wikipedia]").val();
    searchWikipedia(searchCriteria);

})

function processResult(apiResult){

  if (apiResult.query.pages[-1]){
       console.log("No results");
    } else {
       for (var i = 0; i < apiResult.length; i++){
             $('#display-result').append('<p>'+apiResult+'</p>');
       }
   }

}
}); 

So far nothing appends to my html and there's no errors in my console.

Answer

Bruno Garcia picture Bruno Garcia · May 2, 2016

@Ali Mamedov's answer is the way to go (it's from Wikipedia) But the wikipedia link is missing the http:. Also, you can handle the response on your function:

   $(document).ready(function(){
        $('#btn').click(function() {
            $.ajax({
                url: 'http://en.wikipedia.org/w/api.php',
                data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
                dataType: 'jsonp',
                success: processResult
            });
        });
    }); 

  function processResult(apiResult){
     for (var i = 0; i < apiResult.query.search.length; i++){
          $('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
     }
  }