$.getJSON not working on this pen

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();
    var url = wikiSearchURL + query + urlEnding;
    $.getJSON(url, function(data) {

All the log statements print out fine except the ones inside the $.getJSON function. It’s like the code is being completely ignored.

That is because you are submitting a form when you “enter” the input. Use k.preventDefault() to prevent the default behaviour of refreshing the page.

After the fix suggested by @BenGitter you’ll also need to add a &origin=* in your URL’s params, to avoid CORS issues.

1 Like


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.

You would have seen an error (see below) in the console (Ctrl+Shft+I in chrome).

Failed to load https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=fun&format=json: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://s.codepen.io’ is therefore not allowed access.

1 Like

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:


Edit: If you want to keep things neater, you could even use an object for your paramaters:

var wikiSearchURL = "https://en.wikipedia.org/w/api.php";
var queryParams = {
  action: 'query',
  format: 'json',
  origin: '*',
  list: 'search',
  srsearch: ''

Then you modify the srsearch property with the user input and pass the updated object to the $.getJSON method:

    queryParams.srsearch = $("#search").val();
    $.getJSON(wikiSearchURL, queryParams, function(data) {
1 Like

Thank you, this is very helpful!

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