Halkeand
Halkeand

Reputation: 67

Error on AJAX get call with wikipedia API

actually working on a FCC Challenge, i need to make a get AJAX call to the wikimedia API, but i'm struggling with it.

I first searched and finded that i needed to put a personnalized request header, but my problem remain the same, the request seem not to be send, because my eventListener on "load" is not activated when making a request. I checked my url and it is working fine in my browser. Thanks for your help, and here is my code :

// ================ AJAX GENERIC FUNCTION =============================
function ajaxGet(url, callback) {
    let req = new XMLHttpRequest();
    req.open("GET", url);
    req.setRequestHeader( 'Api-User-Agent', 'Wiki Viewer' );
    req.addEventListener("load", function () {
        if (req.status >= 200 && req.status < 400) {
            // Call the callback function and pass it the response
            callback(req.responseText);
        } else {
            console.error(req.status + " " + req.statusText + " " + url);
        }
    });
    req.addEventListener("error", function () {
        console.error("Erreur réseau avec l'URL " + url);
    });
    req.send(null);
}
// ================ FUNCTION(S) =============================

function displayResult() {
let urlToSearch = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchInput.value;
  ajaxGet(urlToSearch, function (response) {
    console.log(response);
  });
}

// ================ GLOBAL VARIABLES =============================
let searchBtn = document.getElementById("searchBtn");
let searchInput = document.getElementById("searchInput");

// ================ EVENT LISTENNER =============================

searchBtn.addEventListener("click", displayResult);

Upvotes: 0

Views: 115

Answers (1)

Huso
Huso

Reputation: 1486

Try onreadystatechange instead of addEventListener

Example code:

req.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      callback(this.responseText);
    }
};

.readyState statusses:

  • 0: Request not initialized
  • 1: Server connection established
  • 2: Request received
  • 3: Processing request
  • 4: Request finished and response is ready

After your comment, I tried your code to see what's the problem, it seems you need to give some more parameters to WikiPedia. See the url: https://www.mediawiki.org/wiki/API:Cross-site_requests

Add &origin=* to the URL and it will work.

Example of your code running: https://jsfiddle.net/cyctreb4/

Upvotes: 1

Related Questions