Has anyone gotten this to work without JQuery?

I’ve worked through this for a while and I’m stuck on the return from the Wikipedia API. I always get a readyState of 4 but the status is 0, so nothing is going through. I’d prefer to use javascript and not JQuery so my script so far is below:

function search(form) {
  var searchInput = form.inputbox.value;
  searchWiki(searchInput);
};

function searchWiki(formData) {

  var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=5&callback=?&search=" + formData.toString();
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.responseType = 'JSON'; // change this for non-JSON links or remove and have it parsed by line 10
  xhr.setRequestHeader( 'Api-User-Agent', 'Example/1.0' );
  xhr.send();
  xhr.onreadystatechange = processRequest;

  function processRequest() {
    console.log(xhr.readyState);
    console.log(xhr.status);
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = xhr.response; // this will be "var response = JSON.parse(xhr.responseText);" for non-JSON data
      //myFunction(response); // myFunction is a function that catches the JSON response
    }
  }
};


Change 'POST' to 'GET' and see if that fixes things.

As @PortableStick mentioned, you need to change POST to GET.

You don’t really need the responseType and setRequestHeader. You should also remove the callback=? from the URL and use origin=* instead to avoid the No ‘Access-Control-Allow-Origin’ header is present on the requested resource. error.

This one should work:

function searchWiki(query) {

  var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=5&origin=*&search=" + encodeURIComponent(query);
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.send();
  xhr.onreadystatechange = processRequest;

  function processRequest() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      console.log(JSON.parse(xhr.response))
    }
  }
}
1 Like

@PortableStick and @zsoltime that did it. I researched for ages and never came across the origin=* . Now I’m getting a response and I can get this done. Thanks for your time!

Here is a good resource comparing jQuery to Vanilla JavaScript.

You might not need jQuery
http://youmightnotneedjquery.com/

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var data = JSON.parse(request.responseText);
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();