Reputation: 67
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
Reputation: 1486
Try onreadystatechange
instead of addEventListener
Example code:
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
.readyState
statusses:
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