Weather Underground API Astronomy - javascript

I am using the Weather Underground API, parsing Json, and getting a result.
For some reason this is not working to get the right astronomy results like so:
http://www.wunderground.com/weather/api/d/docs?d=data/astronomy&MR=1
Moon:
Current:
Sunrise:
Sunset:
Here is what I have so far and am getting no results:(updated)
$.ajax({
url: "http://api.wunderground.com/api/72df18b7f213607b/astronomy/q/CO/Alamosa.json",
dataType : "jsonp",
success : function(parsed_json) {
var hourly = parsed_json['moon_phase']['current_time']['sunrise']['sunset'];
for (index in hourly) {
var newHourlyString = moon_phase[index]['hour'] + ' is ' + current_time[index]['hour'];
var newHourlyParagraph = $('<p/>').text(newHourlyString);
$(".astro").append(newHourlyParagraph);
}
}
});

Try this out. There was a lot missing from your question but I was able to pull info from the video you linked.
You should also work on asking better questions with all necessary details included to get better answers.
$(document).ready(function() {
$.ajax({
url: "http://api.wunderground.com/api/72df18b7f213607b/astronomy/q/CO/Alamosa.json",
dataType: "jsonp",
success: function(parsed_json) {
var moon_phase = parsed_json['moon_phase'];
var moonData = {};
moonData['Moon Ill'] = moon_phase['percentIlluminated'] + '%',
moonData['Moon Age'] = moon_phase['ageOfMoon'],
moonData['Current Time'] = moon_phase['current_time']['hour'] + ":" + moon_phase['current_time']['minute'],
moonData['Sunrise'] = moon_phase['sunrise']['hour'] + ":" + moon_phase['sunrise']['minute'],
moonData['Sunset'] = moon_phase['sunset']['hour'] + ":" + moon_phase['sunset']['minute'];
for (index in moonData) {
if (moonData.hasOwnProperty(index)) {
var newHourlyString = index + ': ' + moonData[index];
var newHourlyParagraph = $('<p/>').text(newHourlyString);
$(".astro").append(newHourlyParagraph);
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="astro"></div>

Related

ajax weird bahavior in url after deleting data in browsers cache

I have a C# Webservice which I'm contacting through URL to retrieve data. The Webservice is lying on a local server in our company network. For example: I have a specific function to get street names, the url to webservice is like this :
Request URL:http://10.1.1.32:8080/webportale_ger_webservice.asmx/SelectStreets
This URL is stored in localStorage.
After deleting browsers cache the request URL has changed, which makes absolutly no sense to me:
http://10.1.1.32:8081/nullSelectStreets
The port is wrong and what about that null?
After trying this request several times again, the url value changes to the correct value.
My jQuery ajax Request looks like this:
var UrlToWebservice = window.localStorage.getItem("url_to_webservice");
$(document).on("keyup", "#input_strasse", function () {
var inputStr = $('#input_strasse').val();
var charStr = inputStr.charAt(0).toUpperCase() + inputStr.substr(1);
console.log("buchstabensuppe: ", charStr)
$.ajax({
type: 'POST',
url: UrlToWebservice + 'SelectStreets',
data: { 'charStr': charStr },
crossDomain: true,
dataType: 'xml',
success: function (response) {
$("input_strasse_datalist").empty();
var strassen = new Array;
$(response).find('STRASSE').each(function () {
var strasse = $(this).find('NAME').text();
var plz = $(this).find('PLZ').find('plz').text();
var ort = $(this).find('PLZ').find('ORT').text();
var arstrasse = $(this).find('AR').first().text();
console.log("arstrasse ", arstrasse)
$("#input_strasse_datalist").append('<option data-ar = ' + arstrasse + ' value = "' + strasse + ' (' + plz + ', ' + ort + ')">' + strasse + ' (' + plz + ', ' + ort + ')</option>')
$("#input_plz").val(plz)
$("#input_ort").val(ort)
})
},
error: function () {
window.location.hash = "httperror";
}
})
})
The value in localStorage is: http://10.1.1.32:8080/webportale_ger_webservice.asmx/
What am I doing wrong?
Thanks a lot.

Utilising the same ajax data for a "refresh all" event (wanting to prevent multiple calls)

So I have a page where multiple containers are dynamically added and filled with html, some of which are populated with data pulled via ajax from a json file. Every 5 minutes the page runs a function that gets every container (marked with class) and for each of them works out its id/index (probably not very efficiently) and does the ajax post.etc.
But the ajax call resulting data is the same essentially for every instance (no limit but on average there would be ~30 ajax calls of the same data for one whole page), it grabs it, decodes it, sorts it, updates html and that is it really.
This feels clunky and im sure will cause issues down the line, is there anything I can do to prevent these 30+ ajax posts without disabling it being 'Asynchronous'/lessen the impact of it?
setInterval(function() {
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
result = data;
var php1 = [result[index].name, result[index].symbol, result[index].price_btc, result[index].percent_change_24h, result[index].price_usd, result[index].id, result[index]['24h_volume_usd']];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
},
error: function() {
alert("error");
}
});
});
}, 300 * 1000);
It seems like your call returns all the data for all the containers already. You don't pass any specific ID into it, and you are filtering the results when you get them, so I will make that assumption.
In that case, all you need to do is move your .each loop inside the ajax success function. That way the ajax runs once, and you just loop through the data when it's received to apply it to the HTML.
I think this should do it:
setInterval(function() {
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
}); //is this really necessary? The server-side could probably sort it more efficiently, esp if it's the result of the SQL query.
result = data;
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
var php1 = [
result[index].name, result[index].symbol,
result[index].price_btc, result[index].percent_change_24h,
result[index].price_usd, result[index].id,
result[index]['24h_volume_usd']
];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
});
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
}, 300 * 1000);

populated jquery objects show as undefined when passed

In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};

Phonegap data storage mechanism using localStorage-adapter.js

How do I use this library localstorage-adapter.js to be able to store data from my server query processing??
I get a library when i see the app from Christophe Coenraets then I want to try it into my application.
My code to access data from server :
$(document).ready(function() {
$('#loading_panel').show();
get_news();
function get_news(){
var serviceURL = "http://www.mydomain.com/api/";
var SistemPakar;
$.ajax({
type : 'GET',
url : serviceURL + 'news.php',
async: true,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType : 'json',
success : function(data){
AllData = data.items;
if(AllData==''){
$('#loading_panel').hide();
$('#empty').show();
}else{
$('#loading_panel').hide();
$('#tampilData').show();
$.each(AllData, function(index, loaddata) {
var data = loaddata.id;
var image = loaddata.img;
var tanggal = loaddata.tanggal;
var strExplode = tanggal.split("-");
var strJoinExplode = strExplode[2]+ '-' +strExplode[1]+ '-' +strExplode[0];
$('#sispakList').append(
'<img src="logo/'+image+'.png"/>'+
'<h4>' + loaddata.judul + '</h4>' +
'<p>' + loaddata.isi +'</p>' +
'<p>' + strJoinExplode + '</p>');
});
$('#sispakList').listview('refresh');
}
},
error: function(jqXHR, exception) {
$('#loading_panel').hide();
$('#conn_failed').show();
}
});
}
});
How do when the data is first captured by the results of the application and use localstorage-adapter.js to save the data as a mechanism that made ​​Christophe Coenraets on the application??

Parsing the json data from google and twitter differences

I am new to javascript. I have worked on twitter API. In twitter API i used jQuery.ajax function to get json data from twitter servers. But when i use the same option with google maps server, my app isn't giving any response the moment it enters the jQuery.ajax. I tried to debug it using jslint, but it came out clean. I used debugging using alert, and it stops when it enters jQuery.ajax function. Is meathod to retrieve data varies with the source ?
If not why isn't my code responding ?
Twitter running function ::
var twitterapi = "http://search.twitter.com/search.json?";
jQuery.ajax(
{
type: "GET",
url: twitterapi,
data:
{
"q": hashtag,
"rpp": 1000
},
dataType: 'jsonp'
}).done(function (response)
{
var results = response.results;
for (var i = 0; i < results.length; i++)
{
$("#tweet").prepend("<li class='tweet'>" +
"<img src='" +
results[i].profile_image_url +
"'/>" +
"<span class='username'>" +
results[i].from_user +
"</span> <span class='tweet_content'> " +
results[i].text +
"</span></li>");
}
});
My google maps API(not working)
var j = 2;
var friends = [];
var distance =[];
$(document).ready(function () {
alert("function started");
$('#button').click(function () {
if (j < 11) {
$('#friends').append('Friend' + j + ':<input type="text" id="friend' + j + '"/><br/><br/>');
j++;
}
else {
alert("Limit reached");
}
});
$('button').click(function(){
var a =[];
alert("button clickede");
for(i=1;i<=j;i++)
{
a[i] = $("#friend" + i).val();
}
var gurl = "http://maps.googleapis.com/maps/api/distancematrix/json?"+
"origins=" +
a.join('|').replace(/ /g,'+') +
"&destinations=" +
a.join('|').replace(/ /g,'+') +
"&sensor=false";
alert("making request to" +gurl);
jQuery.ajax(
{
type: "GET",
url: gurl,
dataType: 'jsonp'
}).done(function (response)
{
alert("request made to"+gurl);
var rows = response.rows;
alert(row[0].elements[0].value);
for(var i=0;i<rows.length;i++)
{
for(var j=0;j<elements.length;j++)
{
distance[i][j] = row[i].elements[j].distance.value;
}
}
alert(distance[0][0]);
});
});
});
I don't know what error are you getting so i can't be of much help.
But the code you posted has three issues:
1- Since a is undefined, i couldn't get past the first two lines.
2- Removing the a calls in the code, then it threw a Syntax Error. I fixed this by removing the last }); line.
3- It made the request, but it threw another error (probably because the URL was malformed).

Categories