So I need to make a a cross domain request where the response is not JSON formatted, so I cannot use .getJSON. .get obviously doesn't work because it is a cross domain request.
I came across this (Read this) when I was googling and it seems it should work for what I want to do (which is do a cross domain call that isn't json formatted using a jquery plug in). My code looks like the following. I know the url works fine because if I paste it into my browser, I can see the response, which according to last.fm documentation
The body of the server response
consists of a series of \n (ASCII 10)
terminated lines. A typical successful
server response will be something like
this:
OK
17E61E13454CDD8B68E8D7DEEEDF6170
http://post.audioscrobbler.com:80/np_1.2
http://post2.audioscrobbler.com:80/protocol_1.2
So I know my URL is fine. Now I am wondering how I get at this information, and why my version of their example does not work.
function performHandshake(sk, token, ts){
var token = md5(apiSecret + ts);
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
$('#container').load(urlToUse);
$.ajax({
url: urlToUse,
type: 'GET',
success: function(res){
var headline = $(res.responseText).find('a.tst').text();
window.console.log(headline);
}
});
}
Well the page you linked you talks about using YQL and jQuery. It's a very interesting solution. However, your example seems to skip over the YQL part (which is crucial).
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
var yqlUrl2Use = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(urlToUse)+
"%22&format=xml'&callback=?"
// this function gets the data from the successful
// JSON-P call
Then you'll have to call the call the new URL as a JSONP req...
$.getJSON(yqlUrl2Use, function(json){
// figure out the format of the answer here...
});
Yeah, cross browser scripting. You can't AJAX anything like that since it violates the same domain policy.
You are going to have to setup a proxy on the same server the JavaScript is running from.
Edit Lookslike you need the $('#container').load(url) bit for that to work.
Go back an reread the linked article carefully.
You need to use $.getJSON rather than $.ajax() to return cross site information.
The var res actually has my information that I needed. I guess their headline = part was specifically for their implementation.
Thanks to those who helped!
Related
I can't seem to figure out how to use USDA REST API no matter how hard I try. I've taken about 6 different online tutorials on how to use REST APIs all of which do not work with this particular API (I'm sure it's something small I'm missing but I've wasted countless hours doing/watching tutorials with no success).
Here's the link to their API:
https://ndb.nal.usda.gov/ndb/doc/apilist/API-FOOD-REPORT.md
Here's what I'm typing in my JavaScript:
xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.nal.usda.gov/ndb/reports/", true);
console.log(xhr.status);
The API says to pass your API KEY in parameters, but that makes no sense to me as every single tutorial I have read does not explain how to pass a KEY as a parameter... If someone would mind taking a moment to write the code necessary to access this API I would be greatly indebted.
UPDATE: I've also tried the JQuery method as follows:
$.get(
"http://api.nal.usda.gov/ndb/reports",
{
"api_key": "API KEY",
"ndbno": "01009"
},
function(data) {
console.log(data);
}
);
With no luck.
UPDATE 2: After leaving the JQuery example in for about 5 minutes, I get an error in the chrome console that says:
XMLHttpRequest cannot load http://api.nal.usda.gov/ndb/reports?api_key=(my API KEY)&ndbno=01009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.
FINAL UPDATE: Problem was with my ISP apparently. Need to deal with that :(
The document you reference has a sample request URL:
http://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=b&format=xml&api_key=DEMO_KEY
You just need to replace the ndbno, type, format and api_key values (the bits that come after the "="). For instance if your API key was 12345, you would need to change it like so:
http://api.nal.usda.gov/ndb/reports/?ndbno=01009&type=b&format=xml&api_key=12345
A complete, albeit "poor", implementation would be:
var apiKey = "DEMO_KEY";
var ndbno = "01009";
var type = "b";
var format = "json";
var url = "http://api.nal.usda.gov/ndb/reports/?ndbno=" + ndbno + "&type=" + type + "&format=" + format + "&api_key=" + apiKey;
$.get(url, function( data ) {
alert( "Data Loaded: " + JSON.stringify(data) );
});
Using the 'DEMO_KEY' provided by USDA I can get back a JSON result using the following code pasted into an HTML file (based on code from your on-going discussion with #BlakeH):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( function() {
$.get(
"http://api.nal.usda.gov/ndb/reports",
{
"api_key": "DEMO_KEY",
"ndbno": "01009"
},
function(data) {
console.log(data);
console.log( JSON.stringify(data, null, ' '))
}
);
});
</script>
No issues with CORS were encountered with this code.
Is there any chance that you submitted more than 1000 requests in the past 24 hours?
I am making a weather website for my school project using the Wunderground Weather API. This is the code I am using to get the JSON data:
$.getJSON("http://api.wunderground.com/api/<apikey>/conditions/q/" + wlocation + ".json", function(data){
alert(data);
});
The <apikey> is where I put my API key, and the $ character is just a shortcut for JQuery.
When I open this webpage, which is local, not published, no alert pops up and I get the error:
XMLHttpRequest cannot load http://api.wunderground.com/api/<apikey>/conditions/q/<myzipcode>.json. Origin null is not allowed by Access-Control-Allow-Origin.
After doing some research on this error, it sounds like I might have to create a web server. However, for the project, we need to turn it in as a folder of .html and other "web files". Is there another way to do this or do I have to make a web server? This project is due soon, so any help is appreciated!
Yes, you can use JSONP for this.
I'm not sure if Wunderground Weather API have some kind of callbacks in JSON. But if they do even jQuery getJSON support JSONP.
Seems like you run into Same origin policy.
here is a code sample from the link that you provided in your original post (http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples). they use JSONP. yes, as #antyrat said, it is a CORS problem.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.
I found this article:
http://msdn.microsoft.com/en-us/library/dd251073.aspx
How could I write 'get' request using jquery.ajax?
You could use the .get() method.
http://api.jquery.com/jQuery.get/
Or just use the regular $.ajax() method (http://api.jquery.com/jQuery.ajax/), which defaults to a GET request.
It depends on whether Bing's API respects the standard ?callback=function method for specifying JSONP callbacks, but if so, then this simplified version of the Search() function should do it:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
$.getJSON(requestStr, SearchCompleted);
}
Keep in mind that neither approach is directly triggering a GET, like you might be used to in AJAX requests to a local server using XMLHttpRequest.
To circumvent the cross-domain restriction on XHR, JSONP works by injecting a new script element into your document which then causes the browser to load (via GET) and execute that remote script. That remote script's contents are a single function call to your callback function, with the entire JSON payload as its parameter.
If that doesn't work, including those Bing-specific callback options should work fine in conjunction with jQuery:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
$.getJSON(requestStr);
}
Keep in mind that, at this point (and somewhat before), you aren't really using jQuery itself for much at all. Even though $.getJSON() or $.ajax() or $.get() seem like they're doing something more powerful than the MSDN example, jQuery is going to do exactly the same thing in this case (inject a script element with its srcpointed at requestStr).
I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding