Weather API not working - javascript

Why am i not getting any data back from the weather api i am trying to update the html tag to show the temperature please help
$(document).ready(function() {
var loc = [];
console.log(loc);
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
});
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It's because when you are calling the second request, the first isn't finished yet, so the lat long values are undefined.
You need to put your second request inside first like this:
$(document).ready(function() {
var loc = [];
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
console.log(Number(loc[0]));
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Location"></div>
<div id="Temperature"></div>

Related

Javascript jQuery function does not define variables

I am new to JavaScript and am trying to run a JavaScript/jQuery function, where Firefox gives me the following error:
Uncaught ReferenceError: latitude is not defined
getHighLow http://localhost:5000/static/weatherballoon.js:54
<anonymous> http://localhost:5000/static/weatherballoon.js:63
weatherballoon.js:54:5
The code being referenced is below.
function getHighLow(){
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```
$.getJSON() is asynchronous. You're trying to use the variables before they're set in the callback.
You need to perform the second getJSON in the first one's callback function.
function getHighLow() {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data) {
const latitude = data.results[0].geometry.location.lat;
const longitude = data.results[0].geometry.location.lng;
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat=' + latitude + '&lon=' + longitude + '&exclude={alerts,minutely,hourly}&appid=' + owmkey, function(data) {
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
});
}
function getHighLow(){
var latitude=0;
var longitude=0;
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```

OAuth Error using Yelp API

I have a sample app that is using Yelp to retrieve reviews and contact information. It was working perfectly until this week.
I'm now getting this error:
Uncaught ReferenceError: OAuth is not defined
function addmarker(lat,lng, id, name, comments){
var yelpcontent = '<h4>' + name + '</h4>';
var phone = '';
var address = '';
var city = '';
var state = '';
var zip = '';
var rating = '';
var terms = name;
var near = 'Indianapolis,IN';
var cll = lat + "," + lng;
var accessor = {
consumerSecret: auth.consumerSecret,
tokenSecret: auth.accessTokenSecret
};
parameters = [];
parameters.push(['term', name]);
parameters.push(['location', 'Indianapolis, IN']);
parameters.push(['cll', cll]);
parameters.push(['callback', 'cb']);
parameters.push(['oauth_consumer_key', auth.consumerKey]);
parameters.push(['oauth_consumer_secret', auth.consumerSecret]);
parameters.push(['oauth_token', auth.accessToken]);
parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
var message = {
'action': 'http://api.yelp.com/v2/search',
'method': 'GET',
'parameters': parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
parameterMap.oauth_signature = OAuth.percentEncode(parameterMap.oauth_signature)
$.ajax({
'url': message.action,
'data': parameterMap,
'cache': true,
'dataType': 'jsonp',
'type' : 'get',
'timeout': 5000,
'success': function(data, textStats, XMLHttpRequest) {
address = data['businesses'][0].location.address;
city = data['businesses'][0].location.city;
state = data['businesses'][0].location.state_code;
zip = data['businesses'][0].location.postal_code;
phone = data['businesses'][0].display_phone;
rating = data['businesses'][0].rating_img_url_small;
yelpcontent = yelpcontent + '<p>' + address + '<br/>' + city + ', ' + state + ' ' + zip + '<br/>' + phone + '</p><p><strong>Yelp Rating</strong></p><p><img src=' + rating + '></p><p><strong>Personal Review</strong></p><p>' + comments + '</p>';
},
'error': function(data, textStats, XMLHttpRequest) {
console.log(name + ' ' + 'did not work');
console.log(XMLHttpRequest);
yelpcontent = yelpcontent + '<p>' + comments + '</p>';
}
});
Can someone please tell me what I'm doing wrong?
OAuth is not defined by default in Javascript.
You have to add it to your page.
Use this code:
<script type="text/javascript" src="http://oauth.googlecode.com/svn/code/javascript/oauth.js"></script>
<script type="text/javascript" src="http://oauth.googlecode.com/svn/code/javascript/sha1.js"></script>
You can see a full example here.

Javascript Geolocation API

Iam trying get the location of the user and than pass it to an Weather API.i need to the location and also to get the API data and insert the location to API url as a coordinates. this is my code and it isn't working :
$(document).ready(function() {
var weatherLocal;
var url = {
"apiKey": "&appid=API_KEY",
"api": "http://api.openweathermap.org/data/2.5/weather?lat=",
"units": "&units=metric",
};
function geoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback);
}else {
console.log("not avialable");
}
}
function successCallback(position) {
url.lat = position.coords.latitude;
url.lon = position.coords.longitude;
}
function preLoader() {
var u = successCallback();
var apiUrl = url.api + u + url.apiKey + url.units;
$.getJSON(apiUrl, getData);
console.log(apiUrl);
}
function getData(data) {
weatherLocal = data;
console.log("the longitude is " + weatherLocal.coord.lon + " and the latitude is " + weatherLocal.coord.lat + " and the description is " + weatherLocal.weather[0].main + " and the city is " + weatherLocal.name + " temperature is " + weatherLocal.main.temp);
}
preLoader();
});

Jquery ajax Check if there results are empty

I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}

jquery javascript problem

Could you please take a look and tell why this isnt working i cant figure it out. the problem is with
$("#item_name").val(item_name);
$("#amount").val(course_price);
This should be adding info to 2 hidden inputs (
<input type="hidden" name="item_name" id="item_name"value="">
<input type="hidden" name="amount" id="amount" value="">
)
but they are coming up as blank
also the value from course_name.php?courseID=1 is Course Name,500
Full Javascript
<script>
$(document).ready(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
$('#course_name').change(function() {
url = "date_range.php?courseID="+$('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID="+$('#course_name').val();
var course_details;
$.get(url, function(data){
course_details= data;
});
split_course_details = course_details.split(',');
course_name=split_course_details[0];
course_price=split_course_details[1];
course_date=$("#date_range").val();
item_name=course_name+' - '+course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
</script>
Place your calculation inside the callback function of $.get(), like this:-
$(document).ready(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
$('#course_name').change(function() {
url = "date_range.php?courseID=" + $('#course_name').val();
$("#dates").load(url)
url = "course_name.php?courseID=" + $('#course_name').val();
var course_details;
$.get(url, function(data) {
course_details = data;
split_course_details = course_details.split(',');
course_name = split_course_details[0];
course_price = split_course_details[1];
course_date = $("#date_range").val();
item_name = course_name + ' - ' + course_date;
$("#item_name").val(item_name);
$("#amount").val(course_price);
});
});
Try this:
$(function() {
var cname = $('#course_name'),
dates = $('#dates'),
iname = $('#item_name'),
amount = $('#amount'),
drange = $('#date_range');
cname.change(function() {
dates.load( 'date_range.php?courseID=' + this.value );
$.get('course_name.php?courseID=' + this.value, function(data) {
data = data.split(',');
iname.val( data[0] + ' - ' + drange.val() );
amount.val( data[1] );
});
}).change();
});
it seems like you're using url variable twice for different data...
try using additional variable..

Categories