I’m writing a small JavaScript program that makes web calls to pull up weather information for when the user clicks on a map. This is my code:
//get the three letter airport code
var text = kmlEvent.featureData.name;
//service to get woeid
var woeid_url = 'http://where.yahooapis.com/geocode?name=';
xmlhttp = new XMLHttpRequest();
//has to be sync, since next request depends on it
xmlhttp.open('POST', woeid_url + text, false);
xmlhttp.send(null);
//now we get the relevent info from the XML
xmlDoc = xmlhttp.responseXML;
woeid_xml = xmlDoc.getElementsByTagName('woeid');
//parse the xml and get the woeid
woeid = woeid_xml[0].childNodes[0].nodeValue;
//with the woeid found, we can make the weather request
weatherhttp = new XMLHttpRequest();
var weather_url = 'http://weather.yahooapis.com/forecastrss?w=' + woeid + '&u=f';
//this is async
weatherhttp.open('POST', weather_url, true);
weatherhttp.onreadystatechange = function() {
if (weatherhttp.readyState == 4) {
alert(weatherhttp.status);
}
}
weatherhttp.send(null);
It makes calls to Yahoo to get the woeid for the location the user clicks. This works and I get the woeid just fine. However, when I make the second call the weather service, it returns nothing and 0 as the status code.
If I change the second part to be sync instead of async, I still get the same error. Does anyone see what I am doing wrong? If I copy the weather_url into my browser, loads it just fine. I don’t understand why the first part works, but not the second. I’m very new to JavaScript and AJAX, so I really have no idea what I am doing.
The browser I am using is FireFox, if that helps.
I’d strongly suggest using a framework such as Prototype or JQuery since you said you’re new to JS, especially when it comes to AJAX. They both big-time iron out and simplify things for you.
My guess to your lack of data is that you’re request is trying to load data from a different domain – See Same Origin Policy. Test out loading something within your domain to see if this is indeed the issue.
Stay away from synchronous AJAX calls! Ideally, you’d do the things that depend on the response of the first request once you receive the data, usually in a callback. Again, this is something that frameworks will let you easily accomplish: Check out the ‘onSuccess’ here