The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution.

For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to make an API call to Wikipedia:

$(document).ready(function() {

  var wiki = "https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json"

  $.getJSON(wiki, function(d) {
    console.log(d);
  });

});

However, this resulted in an error stating

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://conn3cted.uk.tn' is therefore not allowed access.

To resolve this error, I added &callback=? at the end of the GET request (

https://en.wikipedia.org/w/api.php?action=query&titles=Main%20Page&prop=revisions&rvprop=content&format=json&callback=?
)

Although this stopped the error from appearing, I still don't completely understand how callback=? resolves the issue.

Edit: This question differs from the linked one, as I am not discussing JSONP or using <script> tags. Instead, I am curious about why adding callback=? made the API call work.

Answer №1

By appending callback=? at the end of the URL, jQuery transforms it into a <script> tag and initiates a JSONP request instead of using XMLHttpRequest.

The responses provided for this particular inquiry shed light on how JSONP works around the constraints of the same origin policy.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Methods for concealing the title and date when printing web content using JavaScript

When utilizing the window.print method to print out a specific screen, I encountered an issue. I need to hide the date in the top left corner of the image as well as the title (not the big heading) which has been intentionally blurred. I've come acro ...

Will my JavaScript function be triggered when the page is resized while printing?

I have a simple HTML layout where I am using the TextFill jQuery library to automatically adjust the text size based on available space. Everything looks good on screen, but when printed, it seems like the page is resized and the JavaScript needs to be re ...

What is the method to obtain an object as the return value from a click function in JavaScript?

I would like to retrieve the cell value from a table by clicking on a button. I have already created a function called getDetail in JavaScript that is implemented on the button, but I am facing difficulty in returning the value from the function. <butto ...

What is the best approach for managing and obtaining accurate JSON responses when working with PHP API and AngularJS 2 services?

Encountering a backend issue with MySQL, wherein one query is producing a specific dataset: {"candidat":[{"ID":1,"nom":"Danny","prenom":"Hariot","parti":"Quamba","departement":"Ukraine","commune":"Chapayeve"},{"ID":2,"nom":"Shari","prenom":"Adamkiewicz"," ...

Discovering absent data in JSON with the help of Python

I'm encountering an issue where I need to categorize a dataset into completed and incomplete sections. To achieve this, I aim to insert flags like 'complete' in the JSON data structure, as shown in the example below. Here is the dataset tha ...

Middleware for enabling the Cross-Origin Resource Sharing (CORS) functionality to efficiently manage preflight

My CORS configuration is set up globally to handle credentials like this: app.use(cors({ origin: 'https://example.com', credentials: true })) However, there are certain routes where I need to allow OPTIONS requests. Following the documentation, ...

Transfer files seamlessly between different APIs

Is it possible to directly transfer thousands of files (images, pdfs) from one third-party API service to Google Drive API without the need for intermediate storage like an AWS S3 bucket? I already have authentication set up for both APIs. I am considerin ...

Wait for NodeJS to finish executing the mySQL query

I am attempting to send an object from the controller to the view. To keep my queries separate from the controller, I am loading a JS object (model). My model structure is as follows: function MyDatabase(req) { this._request = req; this._connection = ...

Navigating the JSON format with inherited classes: Best practices

I require my web-api to provide a JSON serialized list of Rule instances. [HttpGet] [SwaggerOperation(nameof(GetRules))] [SwaggerResponse(StatusCodes.Status200OK, typeof(List<Rule>), "Rules")] [ProducesResponseType(StatusCodes.Status200OK)] public a ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

Add a fresh text field with the click of a button and delete it with another button in Laravel 4

My form includes two fields: phone and email, as shown in the image below. By clicking on the plus button, I would like to add an additional text field to the form below the button. Similarly, by clicking on the minus button, I want to remove the text fie ...

Retrieving JSON data value without a key using AngularJS

I am struggling to retrieve a data value from a JSON array in Angular that does not have a key value. While I have come across examples of extracting values with keys, I haven't been able to crack this particular piece. The JSON returned from the API ...

The switch/case function I implemented is functioning correctly, however, an error is being displayed in the console stating "Cannot read property 'name' of null"

Check out the live codepen demo here After selecting "elephant" from the third dropdown, the console.log(brand.name) displays "elephant" as expected and executes the rest of the switch statement successfully. However, there seems to be a console error oc ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

Unable to convert JSON data to char array due to a NumberFormatException while using editText

I am attempting to parse JSON on Android, and after parsing the JSON, I want to convert the inputted ID in Edittext to a char array. However, I am encountering a NumberFormatException. I don't think this is a silly question, but where could the prob ...

Timer Does Not Appear to be Counting Down

I recently added a countdown clock to my website, but I'm having an issue with it not updating in real-time unless the page is refreshed. I'm not very familiar with javascript, so I found some code online and made some modifications myself to sui ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

Categorize elements in an array based on a specific keyword

Struggling with my AngularJS (1) application, I can't seem to figure out how to split an array of items into separate arrays grouped by item. In simpler terms, I have an array with different items and I want to group them by their uuid like this: [ ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

Pull data from another domain's DIV using jQuery's load/ajax function

I need to load content from a different domain into a DIV on my JSP page. For example: $("#myDiv").load("https://www.google.com") The issue I'm facing is that the request is being blocked by the browser's same origin policy. I've explore ...