What is the purpose of the callback in the wikipedia API URL?


Here is the API URL : https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=tesla&callback=JSON_CALLBACK


That is a jsonp request described here


jsonp requests are made via a <script> tag in the HTML page which is a bit of a pain - JSON_CALLBACK is the name of your callback function to process the data returned by the <script> tag - something like

function dojsonp(data) {

the <script> tag can be static or dynamic

The wiki doc above mentions the alternative cors request using an origin=* parameter that can be made with XMLHTTPRequest - I had to urlencode “*” below as “%2a” to prevent the url being modified by this forum posting software but you don’t have to do that



Thanks very much.
I will be honest with you, its not crystal clear to me but still I have learned something here.


These are good references for web APIs - they are not easy to grok - use them more as goalposts to get you started kicking the ball


You may get more help on this forum if you tell the forum what you’re trying to do and the issues you face


To expand a bit on the above, in your example, it’s for embedding that URL as a <script> in your page to call a function named JSON_CALLBACK.

Here’s how you would use it directly in your HTML:

  function JSON_CALLBACK(data) {
<script src="https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=tesla&callback=JSON_CALLBACK"></script>

Or, how you would use it with JavaScript instead:
var s = document.createElement("script");
s.src = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=tesla&callback=JSON_CALLBACK";

function JSON_CALLBACK(data) {

You may also notice `callback=?` if you use jQuery - it tells jQuery to replace the question mark with a random number/function name and embed the URL as a script for you like we did above. It's a common way to work around cross origin resource sharing (CORS) errors - since you're running the script directly from your page rather than from the remote server, there is no origin to cross.

Luckily, with the Wikipedia API, none of this is required. Just replace that callback parameter with origin=* and you can make cross origin requests without issue.


To be honest I don’t know, I’m going to try and figure it out at some point, I removed from the URL and my script worked fine.


That was not the case with me, for me after removing the part I didn’t get any JSON.