Alright, so I'm building a web app that provides music information (i.e. info on artists, albums, songs, etc.) and for the info source I'm using the MusicBrainz API.
Now, I'm trying to load the data from an API call and process it, with jQuery. This is the code I'm using:
Code:
queryString="http://musicbrainz.org/ws/1/artist/?type=xml&name="+qry+"&limit=10";
$.ajax({url: queryString, dataType: ($.browser.msie) ? "text" : "xml", success: function(data){
alert("success");
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
};
...
With 'queryString' being the URL string for the request, and then I'd proceed to read the data out of the 'xml' object. Fairly simple.
However, this is where problems arise. The code works flawlessly when running locally on my computer, but does not work at all when I upload everything to my web server and try to run it there. I did some reading and have discovered that AJAX calls can't be made across different domains, due to security issues.
So I've read through numerous solutions, but almost all require either something with PHP (which I have absolutely NO knowledge of) or grabbing the data in JSON format (which apparently isn't subject to the same security restrictions). However, my main problem is that the MusicBrainz API does not return data in JSON format (in fact the only format it returns is XML).
So in any event, I was basically just wondering if anyone could give me some help or pointers on if and how I could grab that remote XML file using only JS/jQuery. Or, point me toward another method that could be accomplished by a complete PHP noob like myself.
Thanks for any help!
You require something on your server side to proxy your request to that other server. A URL that looks like:
/proxy?url=http%3A//musicbrainz.org/ws/1/artist/%3Ftype%3Dxml%26name%3Dexample%26limit%3D10
If PHP is available on your server, you can Google to find a generic PHP proxy script.
EDIT Here is an example of very simple PHP script that will retrieve a specified URL:
<?php readfile($_GET['url']) ?>
Note that you won't be able to POST any data to it, or specify a Content-Type. This is the most basic proxy required for very basic needs.
I understand that JSON is not an option right now but still, here is the explanation of why it can work for cross domain requests.
JSON being Javascript, it can be queried using the <script> tag instead of XMLHttpRequest. Since the <script> tag does not have the same restriction for cross domain request, it is possible to retrieve the JSON content this way.
This technique is called JSONP and is implemented in jQuery in the getJSON function.
If you don't want to setup your own proxy server, check out my response here: use jsonp to get xml cross domain
Related
Could someone explain how I can access Wolfram's API data? I'm not worried about formatting for now--I would just like to learn the basics of interacting with the API.
The Wolfram website FAQ says this: "The Wolfram|Alpha API is designed to operate with interactive web technologies such as AJAX, Flash, and Silverlight."
And the documentation, which is located here: http://products.wolframalpha.com/api/documentation.html, says this: "A simple API call to retrieve output for the query "pi" would look like this:
http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
This query did not specify a desired output format, and the default is to retrieve the plaintext and image representations of each subpod. The image is returned as an <img> tag suitable for direct inclusion in a web page. Here is the output:"
I just have no idea how to put this together to actually access the Wolfram API data. Do I use AJAX or something else? What is the basic code for accessing the data?
I'm very new at this, so any help would be greatly appreciated. Thanks a lot!!
To use XMLHttpRequest their server must enable credentials by setting the Access-Control-Allow-Credentials response header to “true”
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
By AJAX I think they mean your server code should make the request.
In the next example they use Java Server Pages on their own domain to make the request:
https://reference.wolfram.com/webMathematica/tutorial/ApplicationsAJAX.html
Check other answers:
Wolfram API javascript cross origin sharing issue
If you use JQuery, a common javasSript framework, you can make an ajax request as follows
var requestData = function() {
$.ajax({
url: "http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX",
}).done(function(data) {
//data should contain the response from wolframalpha
});
For some reason the National Weather Service's xml site does not work for me. When I say "does not work", I mean that I've tried both XMLHttpRequest and ajax to GET the xml data from http://w1.weather.gov/xml/current_obs/KSFO.xml in order to write a script that displays current weather conditions. this is my code:
(function (){
updateWeather();
})();
function updateWeather(){
var url= "http://w1.weather.gov/xml/current_obs/KSFO.xml";
$.ajax({
url: url,
dataType: 'xml',
error:function(xhr){
document.getElementById("weatherbox").innerHTML="error" +xhr.status+xhr.statusText;},
success:function(result,status,xhr){
document.getElementById('weatherbox').innerHTML="success";
}
});
}
I know that you typically cannot request information cross domain, but the NWS site says its open to the public and im using an ajax call and since it seems as though nobody else has this problem it must not be a cross domain error, but i have tried using crossDomain: true in the ajax call. I have tried making the url "https:...." instead but that did nothing. I've tried specifying type:'GET' in the ajax call as well. Every time I run the script it returns error0error . Does anyone have any ideas? A working implementation of an ajax call would be even better, I've been working at this for days and it's driving me crazy that I can't seem to retrieve this data.
in response to the first comment, I looked into it before but it seems like the SOAP service is for requesting data packages, such as "the weather in SF from january to september" or something, and from the looks of this:
"XML Feeds of Current Weather Conditions
This page provides access to observed current weather conditions for about 1,800 locations across the United States and US Territories. Two file formats designed for computer to computer data transfer are provided. RSS and XML lists are provided to aid the automated dissemination of this information. More information on RSS and XML formats/feeds. Comments and feedback are welcome. There is additional information about this offering via this Product Description Document.
Select a State or Territory to locate XML weather observations feeds available:
Select a State/Territory above to list display list of observations stations An index list of all available stations is available in XML (900kb): XML Format"
and
"About XML
NWS offers hourly weather observations formatted with xml tags to aid in the parsing of the information by automated programs used to populate databases, display information on webpages or other similar applications. This format is not to be confused with RSS and cannot be read by RSS readers and aggregators. These files present more detailed information than the RSS feeds in strings friendly for parsing. Both the RSS and XML feeds offer URLs to icon images. Additionally, A list of what phrases may appear in the XML tag and suggested icons is available. To access these feeds, select a state and then the last XML link in the column."
from this site: http://w1.weather.gov/xml/current_obs/
i should be able to just use the xml from the link i posted above to retrieve current observation data and not packages like one would use for calculating or predicting forecast trends, AND it seems as though the SOAP request service actually would not work for my purposes because i cannot just order one data point.
You could use JSONP request to avoid getting CORS errors, but this SOAP service does not wrap data in script. Just try reading the docs here. You'll most probably have to create a client. NWS also provides a RESTful API. Read the tutorials here.
If you can use a php proxy, then look at http://www.webresourcesdepot.com/cross-domain-javascript-with-simple-php-proxy/ for the solution, and the corresponding code link at pastebin
To summarize, the solution uses an intermediary to the remote site that sits at the same location as your JS code. You invoke the proxy by setting the url parameter to your target. Let's say you saved the proxy code to filename 'weatherproxy.php' and your webserver supports the php module and curl support, then you would set your variable as
var url = 'weatherproxy.php?url=http://w1.weather.gov/xml/current_obs/KSFO.xml';
With no other options to your proxy, on success it will return a json with the form:
{ status: { http_code: 200 }, contents: "your xml contents as a string" }
From there you would have to invoke an xml interpreter on 'contents'. Alternatively, there are parameters that you can supply to that proxy to return the raw xml. The parameter is '&mode=native'. I'm not sure though that jQuery can properly handle the XML that returns.
Have fun exploring the code.
I'm a java script newbie and I'm wonder how I can read the response from a URL into a variable.
Example:
Reading the weather information from NOAA into a java script variable.
var = http://weather.noaa.gov/pub/data/observations/metar/stations/EDDB.TXT
"AJAX" is the technique to load data from a URL. jQuery makes AJAX easier (though you don't have to use it):
$.get('http://weather.noaa.gov/pub/data/observations/metar/stations/EDDB.TXT', function(data) {
// Do stuff with data here
});
Unfortunately, this probably won't work. Unless the web site you're downloading from does something special to allow it, which is not typical (look up CORS), you cannot use AJAX to load data from a different domain because the web browser will block it. For example, if your site is example.com, you cannot download from weather.noaa.gov.
An alternative would be to have server-side code in your web site that would download the content from the URL, acting as a proxy for that web site. Then your web page would download from your own server instead.
$.get('http://example.com/weatherStationData.php', function(data) {
// Do stuff with data here
});
I am trying to implement a simple request to Wikipedia's API using AJAX (XMLHttpRequest). If I type the url in the address bar of Firefox, I get a neat XML, no sweat there. Yet, calling the exact same url with:
// this is my XMLHttpRequest object
httpObjectMain.open("GET", "http://en.wikipedia.org/w/api.php?action=query&format=xml&prop=langlinks&lllimit=500&titles=kaas", true);
httpObjectMain.send(null);
returns an empty response. According to FireBug, I get a 200 OK response, but the content is just empty.
I suspect I might be missing something on the header of the GET http request.
Help! (and thanks!)
The Wikipedia API does support JSONP.
Your query string'll become something like this:
http://en.wikipedia.org/w/api.php?action=query&format=json&callback=test&prop=langlinks&lllimit=500&titles=kaas
But you'll have to build the jsonp handler (or you can use your favorite library to do it), switch to json output format from the xml you choose and create the callback function to parse the result and do the stuff you need on the page.
The browser will not allow you to send an XHR to another domain other than the one the page is on. This is for security purposes.
One way around this that I have seen is to setup a proxy on the domain the page is hosted on that will pass requests through to the actual api server. See http://ajaxpatterns.org/Cross-Domain_Proxy
How do you get around this Ajax cross site scripting problem on FireFox 3?
If you're using jQuery it has a callback function to overcome this:
http://docs.jquery.com/Ajax/jQuery.ajax#options
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?".
jQuery automatically replaces the ?
with the correct method name to call,
calling your specified callback. Or,
if you set the dataType to "jsonp" a
callback will be automatically added
to your Ajax request.
Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script
To update the answer (I guess, mostly for my benefit when I come looking for this answer later on), if are loading XML or something else, you can always ask the user if he will allow us to read from another site with this code:
try {
if (netscape.security.PrivilegeManager.enablePrivilege)
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
alert("Sorry, browser security settings won't let this program run.");
return;
}
(from the RESTful web services book) But, this only works in firefox, when the html file is loaded from local file. So, not that useful.
One more solution: if all you need is the headers, you can specify "HEAD" as the method and it won't trigger the security issue. For instance, if you just want to know if the web page exists.
var client = new XMLHttpRequest();
client.open("HEAD", my_url, false);
client.send(null);
if(client.readyState != 4 || client.status != 200) //if we failed
alert("can't open web page");
Some more details would be nice: which AJAX library are you using, what would you like to achive, how you do it.
For example it can be a cross-domain Ajax request, which is not allowed. In this case use JSON.
I came across this problem recently and it was while I as AJAX loading the local request, not cross site scripting problem. Also, Jimmy himself seems to have the same problem. This seems to be the FF security problem, this article describes the cause and the solution to access to restricted uri denied" code: "1012 problem.
Sorry, got that error using JQuery
$.ajax on FireFox 3. Tried jsonp
suggestion but I think that will only
work with something that will serve up
json. I'm trying to create a sample
local html file based mashup that will
pull data from Yahoo!Finance, but they
are serving .csv, so I think I'm SOL.
– Jimmy Chandra (Sep 9 at 17:20)
I hope you'll find it useful.