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.You can read more about wiki opensearch here.
Get pages whose name matches a given string.
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:
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:
Let`s output response jsonp data in a console:
We access these properties in a each loop for all articles. Finally we insert output in a DOM:
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:
To avoid this, we can simply check if a use input is empty or not: