Wikipedia Viewer

source demo
Stack of technologies: HTML, Sass, jQuery, API
Real-time filtered search to Wikipedia api with ajax requests using JSONP

How it works

In this app we use a Wikipedia API to do a get requests and show first 10 articles on a response from wikipedia. One of the actions that this API provides called open search:

MediaWiki API:Opensearch.
Get pages whose name matches a given string.
You can read more about wiki opensearch here.

We have to use jsonp datatype because of No 'Access-Control-Allow-Origin' header problem in case of simple json. It`s related to a Cross Origin Requests parameters. So we grub search request input every time a user press a key in a search bar and store it in a variable. Then we can compose our url for ajax request:

$('#search').on('input', (e) =>{
  let req = e.target.value;     // grub search input
  let req_url = 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search='+req; 

On a success response we grub an array of articles and output each of them on a screen with a title, desciption and a link to an actual article on Wikipedia:

success: function(data){
  let articles = data[1];
  let output = '';
  $.each(articles, (index, article) => {
    output += `
    <li class = "article_card">
      <a href="${data[3][index]}" target="_blank">
        <h3>${article}</h3>
        <p class="description">${data[2][index]}</p>
      </a>
    </li>`
  });

Let`s output response jsonp data in a console:

We obtain an object with 4 properties:
  • User input
  • An array of relevant articles names
  • Articles description
  • Articles links

We access these properties in a each loop for all articles. Finally we insert output in a DOM:

$('#articles').html(output);

Empty user input problem

If we stop here, the code will work, but what if user will type some letters in the input field and clear it after? We will always see the returned articles on the request by first letter entered by user. Example:

User input data[0]
react r
vue v

data[0] will return the first letter entered by user when he clears out all input:

wiki_pb

To avoid this, we can simply check if a use input is empty or not:

if (req != ''){
  $('#articles').html(output);
}
else {
  $('#articles').empty(); //clear output if no data coming
}