After browsing through this site, I found that you can get Yahoo weather in a JSON format using forecastjson.
When I run:
$.getJSON("http://weather.yahooapis.com/forecastjson?w=2112762724", function(data){
...
});
I get the following error:
XMLHttpRequest cannot load http://weather.yahooapis.com/forecastjson?w=2112762724. Origin null is not allowed by Access-Control-Allow-Origin.
I've gotten this error before but its normally because I'm trying to load XML cross domain but this is clearly JSON. If you go to the link in the getJSON function, it shows JSON data. Does anyone know why I am getting this error?
Thanks
Using JSON doesn't mean that you will not encounter cross domain problem. That is an object standard.
If you want to make a cross domain request, you should use JSONP.
The url that you are trying to request, doesn't support JSONP request. But you can use YQL instead of that.
here is an example,
var query = escape('select item from weather.forecast where woeid="2295424"');
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=c";
$.getJSON(url, function(data) {
console.log(data);
});
And here is the URL that you can check json result.
DEMO
Related
I'm trying to make a simple JSON get request to an API on a domain that I do not control.
My code is simply:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://pubapi.cryptsy.com/api.php?method=marketdatav2',
success: function (data) {
console.log(data);
}
});
});
But since that is a cross-domain request, I am getting this error in the Chrome Console:
XMLHttpRequest cannot load http://pubapi.cryptsy.com/api.php?method=marketdatav2. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
And when I try to add the parameter dataType: 'jsonp' the Console returns with this error:
Uncaught SyntaxError: Unexpected token :
But when I examine the Network tab in Chrome I see that under Headers the Status Code is 200 OK and I can actually see the full response in the Response tab, but the console is still showing the "Unexpected Token :" error and the JQuery JSON request is still failing.
Here's the JS Fiddle link: http://jsfiddle.net/6Qcq2/ You can see the same results
I have tried running the url on http://www.hurl.it and it shows me Status OK and the response as well, so I must be doing something wrong.
I've pretty much wasted the whole day trying to figure out how to get around this problem.
Your help is very much appreciated.
The response from the API is JSON, not JSONP, so just changing the data type doesn't help.
You can use a proxy that makes the request and turns the JSON into JSONP:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://jsonp.guffa.com/Proxy.ashx?url=pubapi.cryptsy.com%2fapi.php%3fmethod=marketdatav2',
dataType: 'jsonp',
success: function (data) {
console.log(data);
}
});
});
Demo: http://jsfiddle.net/6Qcq2/1/
You need to setup some type of proxy script. Due to the Same-origin policy, you can't make an ajax call to a resource that is on an external domain. You can get around this by setting up a simple PHP script that will query the data for you. Then, you would point your ajax call to your script (which will be hosted on your domain). The content type for that resource is application/json, so telling jQuery the type is jsonp won't help you.
AJAX requests do not work cross-domain for security reasons. Since you're reading JSON data, you may be able to make JSONP work.
Shouldn't the jsonp response direct to a callback?
What is JSONP all about?
I'm trying to pull in the total shares from a number of pages and have them displayed on my home page. I'm using addthis for the share buttons. I found a way to pull in the required info using JSON here.
Since I have multiple urls I'm storing them in an array, then cycling through and calling each one. Here's my code...
jQuery(document).ready(function(){
var shareCountArray = [ "url1", //Array to put all url's to get share total
"url2"]
shareCountArray.forEach( function(shareUrl) {
var url = "//api-public.addthis.com/url/shares.json?url=http%3A%2F%2F"+ shareUrl +"?callback=?";
jQuery.getJSON(url, function(json) {
alert(json.shares);
});
});
});
It's throwing up the error "Uncaught SyntaxError: Unexpected token : ". I thought this may have been because I included ?callback=? but when I remove that the console throws up errors because they're different origins.
Thanks for your time!
When you include callback=? then jQuery thinks the response is JSONP. JSONP is nothing else than including a JavaScript file. I.e. the response you receive is interpreted as JavaScript. That also means that if the server returns anything else than valid JavaScript, you will get an error. JSON on its own is not valid JS syntax, that's why you get the that error (you can verify that easily by putting {"foo": 42} in the console).
when I remove that the console throws up errors because they're different origins.
JSONP as well as CORS have to be supported by the server. You can't make an Ajax or JSONP request to the server if it doesn't. See Ways to circumvent the same-origin policy for alternatives.
But it actually looks like the service does support JSONP:
When calling services that support html responses, you may omit the .html extension. Optionally, you can use json mode and pass callback=function to specify a jsonp callback wrapper. Content-Type headers are set on responses as appropriate.
Looking at your URL, it is malformed. You should use &callback=? instead of ?callback=?. Multiple request parameters in a URL are separated by &. ? only indicates the beginning of the query string. E.g.
http://example.com/?param1=value1¶m2=value2
Learn more about URLs: https://en.wikipedia.org/wiki/Url
I tried to get response from my json url in javascript by using below code:
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
alert("get data");
$.getJSON('http://vamdemo2.e-isg.com/vamsyncservices/api/site/GetAllSites?username=Admin&password=password', function(data) {
alert(" data alert"+data); //uncomment this for debug
});
});
});
I didn't got any response from above url. If I changed the url from http://vamdemo2.e-isg.com/vamsyncservices/api/site/GetAllSites?username=Admin&password=password to https://www.googleapis.com/freebase/v1/text/en/bob_dylan, getting response. If I open the both url's in browser, both are having data.. But, when I tried to get response from the url using javascript , one url only given response. Where is the problem?? Why another url not giving any response??
Please give me any solution for this...
Thanks in advance...
I've put your code in my browsers and, for me, both URLs are not working.
Even for the googleapis.com URL, when I load your code in chrome and press F12 I get this error:
XMLHttpRequest cannot load https://www.googleapis.com/freebase/v1/text/en/bob_dylan. Origin null is not allowed by Access-Control-Allow-Origin.
This is because JavaScript typically is not allowed to run on domain1 and load URLs from domain2. This is by design, as a security measure.
If
-you are happy to change your client code above AND
-you can make your vamdemo2.e-isg.com server to alter the response when a "callback" query string parameter is added
Then
-there is a solution to this: JSONP
Read more details about how to implement this here:
http://en.wikipedia.org/wiki/JSONP
I'm horrible at Javascript, so sorry in advance for what I'm going to go ahead and assume is an amazingly stupid question.
I'm simply trying to perform a GET request to GitHub's public repo API for a given user, and return the value as JSON.
Here's the function I'm trying to use:
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'json',
type: 'get',
success: function(data) {
alert('raw data: ' + data)
var json_response = $.parseJSON(data);
alert(json_response);
}
});
}
This is returning Null for data. And in the console, I see Failed to load resource: cancelled. I know the URL is correct, because if I run curl on the url, it returns the expected data.
jQuery's ajax function supports JSONP which allows cross-domain requests (which you need because you're trying to request data from github.com from another domain). Just change the dataType from 'json' to 'jsonp';
function get_github_public_repos(username) {
var the_url = "http://github.com/api/v2/json/repos/show/" + username
$.ajax({
url: the_url,
dataType: 'jsonp',
type: 'get',
success: function(data) {
var json_response = data;
alert(data);
}
});
}
UPDATE: It's import to note that the end pint (in this case github.com's API) has to support JSONP for this to work. It's not a guarnateed solution for ANY cross-domain request as pointed out in the comments.
JavaScript is subject to cross-domain restrictions when making requests on a different server.
Well, unless you run your code in the github.com domain, that won't work.
You can use simle ajax only in your domain.
One solution is to create a proxy for it. Make a page on your server that does one thing, gets your requested (out of domain) content with curl, and prints it. Then you call this proxy with ajax.
The XmlHttpRequest object (which $ajax uses) cannot download content from a different domain due to the same origin policy. You would need to use something such as JSONP to be able to do this from a browser.
As the others have said, you cannot execute ajax on a remote domain.
You will need to write a server sided script on your domain (such as php), that will do the dirty work retrieving the information needed from the github domain.
Then, use your ajax to query your server side script for the information.
I know the URL is correct, because if
I run curl on the url, it returns the
expected data.
Use that idea to get your ajax working. Create a proxy page on your site that uses curl to retrieve the data you want, then have your "the_url" variable point to that page on your site. Cross-domain restrictions prevent you from being able to use ajax in the manner you attempted.
I am trying to get json data from a url. Url is working ok in FF. I am trying code like this
$.getJSON("http://testsite.com/1234/?callback=?", function(data){
//here i am getting invalid label error**
}
);
When i am trying without callback=? i am getting empty data
$.getJSON("http://testsite.com/1234/", function(data){
//here i am data = ""
}
);
Whats going wrong?
It looks like the site you're fetching from doesn't support JSONP, with this URL:
http://testsite.com/1234/?callback=?
It's trying to use JSONP, but the server is returning a plain JSON response (not wrapped in a function).
With this URL:
http://testsite.com/1234/
It's not trying JSONP at all, and being blocked by the same-origin policy.
To fetch data from a remote domain, it needs to support JSONP so it can be grabbed with a GET request, so you'll need to either add support to that domain, or proxy the request through your own.