Accessing data from another domain using JavaScript with Cross-Origin Resource Sharing (

After researching various CORS and JSON request discussions, I find myself puzzled as to why the first script functions correctly while the second one does not. I am eager to enhance my understanding of CORS, Javascript, XMLHTTPRequest2, and AJAX.

The following code works:

function wfs() {
 var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles&callback=getRoute';
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.getElementsByTagName('head')[0].appendChild(script);
}

function getRoute(response) {
 console.log(response);
}

The following code does not work:

function wfs() {
 var url = 'http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles';
 var xhr = new XMLHttpRequest();
 xhr.open('GET', url, true);
 xhr.onload = function(e) {
  if (this.status == 200) {
    var json = this.response;
    console.log(json);
  }
 };

 xhr.send();
}

Firebug displays a Red 200 Null Response for the second code snippet.

Interestingly, the second script successfully executes when a different URL is used:

var url = 'http://ip.jsontest.com/?mime=2';

Answer №1

One of the domains,

http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/51.22545,4.40730,%5B51.22,4.41,51.2,4.41%5D,51.23,4.42/car.js?lang=de&units=miles
, lacks CORS implementation (does not include a valid Access-Control-Allow-Origin header). On the contrary, http://ip.jsontest.com/?mime=2 has this feature. Unfortunately, it is beyond your control as it depends on the server.

The first code snippet utilizes JSONP which involves injecting a script tag into the document. These script tags can have external sources but might be blocked for security reasons if they are not of the same scheme. This mechanism allows the server to transmit javascript code that you embed in a <script> tag and execute instantly.

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

The functionality of changing the checkbox to "checked" by clicking on the span is not

How can I create a toggle button with a checkbox using css and jquery? Clicking on the span representing the toggle button should change the checked property of the checkbox. Currently, the span does not change the property, even though it triggers the c ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

Guide on generating a chart in PHP by utilizing JSON data fetched from a SQL query

After successfully creating a pivot table using an SQL query, I executed it in PHP through 'multiquery' and converted the results into JSON format using 'json_encode'. The JSON data consists of approximately 25 million records, each wit ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

Guide to attempting an asynchronous function again in JavaScript with a time delay

I've been facing a challenge while trying to retrieve a record from a database. The issue of race conditions often leads to situations where the record might not be available when attempting the initial fetch. How can I implement retry logic to overco ...

Leverage nan for the transmission and retrieval of Float32Array within an addon module

I am currently attempting to utilize nan in order to perform calculations on an array of floating point numbers within an add-on and then return the result as a Float32Array. However, while the arguments have IsNumber() and NumberValue() functions, there ...

There was a lack of information received from the callback function when utilizing jQuery AJAX with JSON in PHP

I've been experimenting with the code found here: https://gist.github.com/Exeu/4674423. This particular code is designed to connect to Amazon's wsdl and fetch product information. Unfortunately, I've encountered some difficulties in getting ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Utilizing deployJava.runApplet for precise element targeting

After years of successfully maintaining an applet that utilizes the traditional: <script src="foo.js"></script> method for embedding a Java applet, we can no longer ignore the need for change. It's time to switch to: deployJava.runAppl ...

Obtain the text content in cases where the DOM is missing both the title and value fields

I am trying to extract the value from a text-box using selenium, but the text-box is marked as readonly and aria-live is set to off. Here is the DOM structure: <input autocomplete="off" class="abc" type="text" role="t ...

Can applications on Windows 8 operate using JavaScript, HTML5, and CSS3 that adhere to industry standards?

As a .NET developer, I tuned in to the keynote for the Build Event in Anaheim, California and had some questions regarding the new support for creating Windows 8 applications using JavaScript, HTML5, and CSS3. They showcased several examples and mentioned ...

Learning how to work with JSON data in PHP

I encountered an issue with a JSON object stored in a variable named $product. The JSON object is as follows: {"id":30} However, when I attempted to access the value stored within, I received the error message: Trying to get property of non-object Th ...

What is the mechanism behind ajax operation on a wame server?

Hello everyone, I'm diving into learning AJAX for the first time by following tutorials on w3schools. Despite my best efforts to follow the step-by-step instructions, I am struggling to make an AJAX example work. Could someone please assist me? Thank ...

Find all strings in the array that do not begin with a letter from the alphabet

When a specific button is clicked, I need to filter the example array provided in the snippet below. The expected output should only include elements that do not start with an alphabet. I attempted: const example = ["test", 'xyz', '1 test& ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

What steps should I take to make my Vue JS delete function operational?

As I work on developing my website, I've encountered some challenges. Being new to coding, I'm struggling with creating a functional delete user button. When I click delete, it redirects me to the delete URL but doesn't remove the entry from ...

Ways to verify if element has been loaded through AJAX request

I am trying to determine if an element has already been loaded. HTML <button>load</button> JS $(document).on('click','button',function () { $.ajax({ url: 'additional.html', context: document ...

The issue with Grid component in Nested Single file Component

I'm currently working on creating a grid component in Vue to set up a sortable and searchable chart using Single File Component. I've also integrated vue-router into the project. Below are my two .vue files. At the moment, I can only see the sear ...

Unable to Preview jQuery Video in Div After PHP Validation, But Image Preview Works Fine

Successfully utilizing the code below (with variations in IDs, etc.), I am able to preview a banner image in a div after PHP validates the upload using AJAX. This process is working perfectly without any issues. However, I am encountering an issue when at ...

Increase the current time by 50 minutes

I have a dropdown menu with various time options like this: <select name="" id="delyvery-hour"> <option value="18:00">18:00</option> <option value="18:05">18:05</option> <option ...