I’ve gotten $.getJSON to work just fine on another pen, but on this one, nothing. It’s as if it’s being completely ignored. I don’t see any errors showing up in the console, and I have not been able to figure out what is wrong.
var wikiSearchURL = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=";
var urlEnding = "&format=json";
$("#search").keypress(function(k) {
if (k.which == 13) {
var query = $("#search").val();
console.log(query);
var url = wikiSearchURL + query + urlEnding;
console.log(url);
$.getJSON(url, function(data) {
console.log("success");
console.log(data);
});
}
});
All the log statements print out fine except the ones inside the $.getJSON function. It’s like the code is being completely ignored.
After the fix suggested by @BenGitter you’ll also need to add a &origin=* in your URL’s params, to avoid CORS issues.
Can you please explain? The link works fine when I just drop it into the web browser. Where to do I insert this into the link, and what does it do/how would i have known to do this? It was not in the api protocol that I saw.
When you make a request from a domain to another, you basically have to tell where you are coming from. The “*” in origin, is used to make anonymous requests and allow access from anywhere (which in your case, is codepen).
As to where to insert it, you just need to add it in your URL like any other paramater. In fact, you don’t even need the urlEnding var; you can add &format=json where you prefer; order isn’t important:
I encountered the same problem. I was tempted to say “It’s all $.getJSON’s fault”. After adding that “&origin=*” bit I discovered yet another issue with the way I was interacting with the API. I had also forgotten to include “&format=json”!
I reply to give visibility to this vital piece of information that I failed to pick up from any other source. Thanks @noyb