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.
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
});
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
I have built a web application that accepts a Member_ID # from the client (javascript). The Member_ID is stored as a var in my javascript… now I need to make queries with it…first query to get member information (name) and then join tables to gather information for health plans that the member is elligible under … and so on.
As far as I can remember the concept is… send a async request to the server and wait for a response, once the response is received, store it and then parse it to extract useful information.
The end goal is to use the 'useful' information to plot graphs using HTML5 Canvas.
I need some direction with how to make the query? because when I read this forum, it is recommended that client-side query is 'bad' for a plethora of reasons.
Since most of my stuff is happening in the client side... few things in C# asp.net...how do I proceed?
It is also important to note that the web application should be accessible via the internet. outside the local network.
Does it make sense to Call a Web Service from the Client Side Using the AJAX Extension Toolkit??
You must handle it server side. Think about the ajax request as a simple POST or GET in the format of ?member_id=123&time=321 pointed at your handler file.
In your handler file you can construct your query from the request variables, execute it, and give a response by printing to the screen in either JSON or XML format.
Take a look here:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.getJSON/
I am trying to retrieve data from an XML file that is not located on my site's server, and then use that data fro various things, such as charts. Here is one example: http://forecast.weather.gov/MapClick.php?lat=40.78158&lon=-73.96648&FcstType=dwml. This is an XML file with the weather data for central park. I want to retrieve the data that is in the <value>tag, which is in the <pressure> tag, so I can create a graph with barometric pressure. I would prefer to do this with JavaScript, but I don't think it's possible to do so when the file isn't on my server.
Note: I do not want a different solution to retrieve the pressure data from somewhere else, because I want to retrieve other pieces of data from other XML files as well.
There's an interesting article about using Yahoo! Pipes to transform Xml weather data to JSON and use the result in a web page without need for any server side stuff (PHP, curl, etc.).
EDIT
Being new to jQuery myself, I a had to dig a little more to find out that (almost) everything described in the first article can be condensed down to
$.getJSON("<your Yahoo pipes url here>&_callback=?", function (data) {
alert(data.value.items[0].data[0].parameters.wordedForecast.text[0]);
});
using jQuerys builtin JSONP.
Pitfall!
Beware that Yahoo expects the callback url param to be named _callback
Nice summary on Cross-domain communications with JSONP which helped a lot to come up with this answer.
If your javascript code is on a server (as opposed to a mobile device), have PHP code load the xml, escape it and insert it into the HTML page. Then you just have to grab that in your code and process it with DOMParser.
You could use curl to pull the data to your server and act on it from there.
curl -o data.txt "http://forecast.weather.gov/MapClick.php?lat=40.78158&lon=-73.96648&FcstType=dwml"
This will give you the information in a file called data.txt. You could then either parse it server side and then just give the bits of data needed, or make the whole file available to your client, since they are both now in the same domain.
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