Using a variable URL in a JSON-call, not working? - javascript

I'm trying to make a simple weather app and it seems I can't access any information using my variable for the JSON-link. Heres my code:
$(document).ready(function() {
var key = 'a91a892f1f2a1aa3f7409a78f72af675';
var locationURL = 'http://ip-api.com/json';
var longitude;
var latitude;
//Getting the geolocation from the user
$.getJSON(locationURL, function(data) {
longitude = data.lon;
latitude = data.lat;
var url = 'api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=' + key;
console.log(url);
$.getJSON(url, function(data2){
console.log(data2, url);
});
});
});
But I get no return from the second JSON-call, and it seems like the variable 'url' is broken or something. What am I doing wrong or not seeing here?

You're missing protocol:
var url = '//api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=' + key;

get: function(req, data, callback) {
data.gym_hash = this.gym_hash;
console.log(data);
$.ajax({
url: rest.server + req,
type: 'GET',
data: data,
success: function(result) {
callback(result);
}
});
}
I use this type if code and let js and jQuery do the magic of formatting the parameters into the url. Call is like this:
get(
"Path/To/Rest",
{
email: email,
password: password,
},
function(result){console.log(result);});

Related

accessing variable value outside of function

I have 2 functions in my script. The purpose of function #1 is to produce a url called "mapsURL"
The purpose of the second function is to run an .ajax request with "mapsURL"
However I am having issues with accessing "mapsURL" in the second function. I declared "mapsURL" in the first function without a "var" in fornt of it. From my understanding, this should make the this the value global and I should be able to access it form inside other functions. Is my understanding incorrect or what am I missing here?
here's my js:
note: I removed my API key for this post, so that's not the issue
$(document).ready(function (){
navigator.geolocation.getCurrentPosition(function (position) {
var positionLat = position.coords.latitude
var positionLon = position.coords.longitude
mapsURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + positionLat + "," + positionLon + "&key=***mykeygoeshere***";
});
function getData (){
$.ajax({
url: mapsURL,
dataType: 'json',
success: function(response){
console.log(response);
}
});
};
getData();
});
getCurrentPosition is asynchronous. It doesn't assign to mapsURL immediately, so when you call getData synchronously, mapsURL hasn't been populated yet.
You should call getData inside the getCurrentPosition callback - which will also allow you to avoid using a global variable:
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var positionLat = position.coords.latitude
var positionLon = position.coords.longitude
var mapsURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + positionLat + "," + positionLon + "&key=***mykeygoeshere***";
getData(mapsURL);
});
function getData(mapsURL) {
$.ajax({
url: mapsURL,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
}
});

Javascript Unexpected run order

I have this jquery / javascript code below. It ask user for location permission, and then outputs a URL string with latitude appended at the end.
I put 3 console.log statemnets to highlight problem, with current outputs I get.
Expected Debug Values (in order)
1_lat =95.555555
2_lat =95.555555
3_https://fcc-weather-api.glitch.me/api/current?&lat=95.555555
Actual Debug Values: (in order)
2_
3_https://fcc-weather-api.glitch.me/api/current?&
1_lat =95.555555
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
});
}
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
I must not be understanding something with how javascript is loading and how jQuery document.ready.function is affecting the results.
navigator.geolocation is async. So you have to wait for the navigator.geolocation.getCurrentPosition callback function before you can process the lat and lng
You can do something like this:
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
}
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
This will result to:
1_ lat=1.xxx
2_ lat=1.xxx
3_ https://fcc-weather-api.glitch.me/api/current?&lat=1.xxx

Code alerting 'object Object'

My code is this:
var username = "john";
var password = "doe";
var url = '//api.bos2.cf/?type=verify&username=' + username + '&password=' +
password + '&callback=?';
$.getJSON(url, function(data) {
success: readData(data)
});
function readData(data) {
alert(data);
}
Although this code alerts object Object instead of {'success' : false, 'msg' : 'Unknown API function'}
Any Ideas as to why this is happening??
Thanks,
CSF
You are trying to display the raw object. You need to turn it into a string first:
function readData(data) {
alert(JSON.stringify(data));
}
function readData(data) {
alert(data.success);
alert(data.msg);
}
just go through simple way.

Trying to get local weather

I am trying to get local weather by getting currentposition and passing it to url for getting results. I can't seem to be able to pass the coordinates outside the getCurrentPosition.
My codepen is: http://codepen.io/rush86999/pen/MKMywE
if (navigator.geolocation) {
//position.coords.longitude
var app = {
getGeoLoc: function(id) {
var self = this;
navigator.geolocation.getCurrentPosition(function(position) {
var myVar1, myVar2, myVar3; // Define has many variables as you want here
// From here you can pass the position, as well as any other arguments
// you might need.
self.foundLoc(position, self, myVar1, myVar2, myVar3);
}, this.noloc, {
timeout: 3
});
},
foundLoc: function(position, self, myVar1, myVar2, myVar3) {
this.latituide = position.coords.latituide;
this.longitude = position.coords.longitude;
console.log('#4 position coords work in foundLoc: ', this.latitude, this.longitude);
},
latitude: '',
longitude: ''
};
console.log('#5 found loc in app, ', app.foundLoc);
var url = 'api.openweathermap.org/data/2.5/weather?lat=' + app.latitude + '&lon=' + app.longitude + '&APPID=7bda183adf213c8cfa2ef68635588ef3';
//lets look inside url
console.log('#1 url has coordinates: ', url);
Theres a few issues here.
Firstly, you don't seem to be calling the getGeoLoc method, so that would be the first fix.
You have included an error callback of this.noloc but it isn't included in your object.
There are a few typo's for your co-ordinates
You are making your API request before the geolocation has resolved so app.latitude and app.longitude will be undefined. This should ideally be wrapped in a method that gets called upon a successful geolocation request.
var app = {
getGeoLoc : function (id) {
//Removed timeout option due to error
var options = {}; //{ timeout: 3 };
navigator.geolocation.getCurrentPosition(this.foundLoc.bind(this), this.noloc, options);
},
foundLoc : function(position) {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
console.log('coords ', this.latitude, this.longitude);
// Call your get weather function
// Using call to bind the context of `this`
this.getWather.call(this);
},
// Error method
noloc: function(err) {
console.log(err.message);
},
// Method to get your weather after location is found
getWather: function() {
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.latitude + '&lon=' + this.longitude +'&APPID=7bda183adf213c8cfa2ef68635588ef3';
console.log('URL is: '+url);
$.getJSON(url, function(data) {
console.log('Your weather data', data);
// Do your dom stuff here
});
},
latitude: '',
longitude: ''
};
// Make sure to call your initialising function
app.getGeoLoc();
NOTE: I have removed the HTML stuff for the demo and have removed the timeout option as it caused an error.
Link to forked codepen

GiantBomb API Work

I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax

Categories