0

I am trying to get article from Wikipedia base on user's input. But the code is not working and I can't figure out the error(s) in my code.

var wResult = document.getElementById("result");
var summary, articleTitle, apiUrl;
function getResult(){
var inputTitle = document.getElementById("title").value;

 apiUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&indexpageids=1&redirects=1&formatversion=latest&srsearch="+inputTitle+"&srlimit=10";

  $.getJSON(apiUrl, function(response){
 summary = response.query.search[0].snippet;
     wResult.innerHTML = summary; 
  });

}
var inputBtn = document.getElementById("btn");
inputBtn.addEventListener("click", getResult);

Here is the HTML code:

<body>
  <h1 class="text-center"> Wikipedia Viewer </h1>


  <form class="col-lg-4 input-group" name="search" id="form">

    <input type="text" id="title" placeholder="Search title" class="form-control">

    <span class="input-group-btn">
      <button type="button" class="btn btn-secondary" id="btn">Go!</button>
    </span>
  </form>


  <div id="result">

  </div>
</body>

You can check it here.

Abk
  • 2,137
  • 1
  • 23
  • 33
  • 1
    The error says *XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&indexpageids=1&redirects=1&formatversion=latest&srsearch=duck&srlimit=10. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.* – Quentin Jun 06 '16 at 16:20
  • @Quentin There's a specific workaround for accessing the MediaWiki API which I've detailed in an answer. –  Jun 06 '16 at 16:23
  • To clarify Quentin's comment, the browser tells you the error but you need to look for it yourself (it won't print on the page). In Chrome (I don't know what browser you use but apparently everybody uses Chrome nowadays) you can just hit F12 and click on "Console" and "Network". – Álvaro González Jun 06 '16 at 16:27

1 Answers1

0

To make a cross-domain request to the MediaWiki API, you must either use format=jsonp or pass an appropriate origin parameter to the API. For details, see the MediaWiki documentation on Cross-site requests.