Ajax call to API not working - javascript

I am trying to retrieve data from an API using Jquery's ajax(), but it doesn't work with this implemenation:
$.ajax('http://api.forismatic.com/api/1.0/?method=getQuote&format=json').done(function(data) {
alert(1);
alert(JSON.stringify(data));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
After running the code the alert function doesn't work, so I concluded that the success callback function isn't working, but I have no idea why.

After inspecting the server response headers, there is no Access-Control-Allow-Origin, this means that the server doesn't allow cross-origin access. Since you make a cross-origin HTTP request, your request will be rejected by the browser following the Same-origin policy:
The same-origin policy restricts how a document or script loaded from
one origin can interact with a resource from another origin. It is a
critical security mechanism for isolating potentially malicious
documents.
Look at your console you will see the following error (Chrome):
XMLHttpRequest cannot load
http://api.forismatic.com/api/1.0/?method=getQuote&format=json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://s.codepen.io' is therefore not allowed
access.
For more details please refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Related

Load large json file from external website with D3

On my site "mywebsite.com" I have a D3 javascript code running on some data set located at "otherwebsite.com/data.json", so I naively tried
d3.json("otherwebsite.com/data.json", function(error, json) {
if (!error) {
console.log('done loading',json)
} else {
console.log(error)
}
})
but of course it does not work :)
Access to XMLHttpRequest at 'otherwebsite/data.json' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Anyone has a better idea? I should emphasize that it is a large file (200MB).
Thanks
Taken from the MDN page on CORS:
For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.
The CORS header in question is Access-Control-Allow-Origin which needs to either be explicitly set to https://mywebsite.com or be set to something that includes that, such as *.
If you have access to the server for "otherwebsite.com" you can change the header being sent with the request.
Otherwise you'll probably have to download the data server side on "mywebsite.com" and then have the front end request it from your back end, rather than making a cross origin request, so you'll change the JS to look like:
d3.json("/data.json", function(error, json) {...

What is the difference between getJSON() function and post() function when make a request across domain?

I am trying to access a Google Apps Script WebAPI from my website using javascript to pass some value and create an excel file and download it through this API.
I tried 2 following way:
Using POST request with $.post.
My values are many. So, at first, I use a POST request with a body is JSON of list values. Browser rejects API response, because of CORS error.
I researched about CORS to understand it. At some topics, I found a solution is the following second way.
Access to XMLHttpRequest at 'https://script.google.com/macros/s/xxxxxxx' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Using GET request with $.getJSON.
I pass JSON of list values to URL parameter and make GET request. It worked fine.
var url = 'https://script.google.com/macros/s/' + api_id + '/exec?' + request_parameter_string;
$.post(url, payload, function(data, textStatus) {
// Do something
}, 'json');
$.getJSON(url, function(json_result) {
// Do something
})
.fail(function() {
// Do something
});
What I do not understand is why? Why it works with getJSON but not work with post?
I think CORS work with both of GET and POST requests. And I checked the response header with Postman. The headers are the same Access-Control-Allow-Origin →*.
I think have something is different inside getJSON and post functions.
*UPDATE: Update POST CORS error message.
GET requests are not bound by CORS we can host images and static files in CDN which is different from the origin and would help in improving the performance by caching and making parallel requests.
Similarly GET is used for serving ads, trackers and analytics from third party domains as well.
More information about Same Origin Policy and GET is at https://security.stackexchange.com/a/16221/9517
How the browsers identify Other HTTP Verbs are allowed for the cross origin request is elaborated # https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

No 'Access-Control-Allow-Origin' header is present (CROS)

From html page using javascript ajax call am trying to call Login_check api (REST webservice) but am getting error as below.
XMLHttpRequest cannot load
http://184.30.53.119:8080/Automation_test1/TRTS/login/Login_Check. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
JavaScript has a same-origin policy. Which means it cannot request pages on other domains. You have a couple of options to do this, use JSONP or have a php script that you call to query the api.
More information: Working With and Around the Same-Origin Policy

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net'

Getting the below when doing a JQUERY ajax call in jsfiddle
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access. The response had HTTP status code 404
URL works fine when I put it in a browser?
Does not work in JsFiddle?
var URL="http://query.yahooapis.com/v1/public/yql&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json&q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22ACM%22)%0A%09%09";
$.get(URL).done(function (data) {
alert("HELLO");
}).fail(function (jqXHR, textStatus) {
alert("NOPE");
}).always(function () {
alert("OH WELLL");
});
I was struggling with the same problem on both JSFiddle and Codepen. I needed to load an external js-data file and it was blocked due to browser-security. My workaround was to include the whole js-data as script with HTML in the header:
<script src="http://yoururlto/yourdata.js"></script>
The data js itself looks like this:
var data = {
"type": "FeatureCollection",
"features": [{
}]
};
Then access the data in any way you want:
geojsonLayer.addData(data);
map.fitBounds(geojsonLayer.getBounds());
This is a standard CORS response when an XHR call is made from the browser. The server needs to allow the domain/location of the browser to make requests.
res.header('Access-Control-Allow-Origin', '*');
Otherwise, the server will block incoming requests.
Another way to get around this is to use a known server as a proxy to make requests to the external API.
It's because your API does not return a CORS header. This header can restrict what hosts to allow access to that specific page and this behaviour is embedded in the XMLHttpRequest functions that jQuery uses. It's used as security measure so there isn't really a workaround for it.

Ajax call using jsonp not working, "Uncaught SyntaxError: Unexpected token"

Problem
I'm working with a open data, city API for river levels, but when I make my ajax call using jsonp I receive an error for Uncaught SyntaxError: Unexpected token < which doesn't appear to be coming from my scripts.js
It is also my understanding that my ajax call might not be working because this API only spits out XML or json. I've tried to switch my dataType: json, but when I do that I receive the error below. Not particular sure if using jQuery's .getJSON is the best method to grab this data?
Data: http://opengov.brandon.ca/OpenDataService/opendata.html
Documentation: http://opengov.brandon.ca/api.aspx
Error (when switching dataType: json)
XMLHttpRequest cannot load http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
scripts.js
$(function(){
$.ajax({
url: 'http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel',
type: 'GET',
dataType: 'jsonp',
success: function(response){
console.log(response)
}
});
});
You may be interested in reading What are the differences between JSON and JSONP?
A "JSONP response" from a server is actually an executable script. The client runs the executable script, and the script happens to contain the data you want, supplied as an argument to a function. If the server doesn't serve an executable script, that server does not support JSONP.
For your next error, see "No 'Access-Control-Allow-Origin' header is present on the requested resource". Ajax requests to other domains are not permitted, unless explicitly allowed by CORS headers (like the Access-Control-Allow-Origin response header) from the server. Due to the same-origin policy, scripts on one origin are not allowed to access the contents of another origin. Cross-Origin Resource Sharing (CORS) is a way for the server to relax the same-origin policy.
I would suggest contacting the providers of the API and requesting CORS support. In this case, it really is as simple as serving an Access-Control-Allow-Origin: * header in the response. Per the W3C's own security recommendations for CORS:
A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*".
Alternatively, you can set up a reverse proxy server that fetches the API resources for you and serves them on your own origin, as noted in an answer on Ways to circumvent the same-origin policy. Since the same-origin policy is a browser restriction, you can have any server you control fetch the API resource and then serve the response to your browser.
The default data format is XML, but can be changed by setting the format query variable to "json" to return JSON formatted data.
You need to add &format=json to the end of the URL:
http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel&format=json

Categories