0

I'd like to use wikipedia search api from javascript, I know it might be easier with something like jquery but I'd like to get a good grip on the basics before using frameworks. Here is the code I wrote, but I never get the alert:

document.getElementById("go_search").addEventListener("click", () => {
    let wiki = new XMLHttpRequest();
    wiki.addEventListener("load", () => {
      alert(wiki.responseText)
    });
    wiki.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Albert+Einstein");
    wiki.send();

  })

The wikipedia adress is a search Albert Einstein, which is just to test if the code is working. Thanks for your help it is much appreciated!

4
  • There is an error in the console which will tell you the problem Commented May 26, 2017 at 13:34
  • Instead of listening to the load event, listen for the onreadystatechange event. The you can check the readyState and status of your XMLHttp object to know the status of the ajax call Commented May 26, 2017 at 13:39
  • Just a heads-up on the future :) Fetch API -> fetch("https://en.wikipedia.org/...").then(response => response.json()).then(res => console.log(res)) Commented May 26, 2017 at 13:50
  • Thanks @Andreas, I did see the error and the fetch API seems like it would be really useful, appreciate the advice. Commented May 26, 2017 at 13:53

1 Answer 1

1

Add origin=* to the URL query params to make JSON API requests to Wikipedia.

Change your request URL to

https://en.wikipedia.org/w/api.php?origin=*&action=query&format=json&list=search&utf8=1&srsearch=Albert+Einstein
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Abhijit, it worked. what the origin does is allow request between different domains right? will it work with any api or just wikipedia?
The Origin header tells the server from which website the client code originated. origin=* is just for the Wikipedia API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.