JQuery $.getJSON confused me - javascript

I am completely confused by the $.getJSON function!
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json', function(data) {
$('#weather').html('<p> Humidity: ' + data.current_condition.humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.current_condition.temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.current_condition.windspeedMiles + '</p>');
});
This is the json that is at that url is:
{
"data":{
"current_condition":[
{
"cloudcover":"0",
"humidity":"82",
"observation_time":"04:07 PM",
"precipMM":"0.2",
"pressure":"997",
"temp_C":"11",
"temp_F":"52",
"visibility":"10",
"weatherCode":"356",
"weatherDesc":[
{
"value":"Moderate or heavy rain shower"
}
],
"weatherIconUrl":[
{
"value":"http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0010_heavy_rain_showers.png"
}
],
"winddir16Point":"WSW",
"winddirDegree":"240",
"windspeedKmph":"26",
"windspeedMiles":"16"
}
],
"request":[
{
"query":"Lat 51.24 and Lon -1.15",
"type":"LatLon"
}
]
}
}
It must be something to do with my syntax!

Try to pass callback=? as the callback function for using jsonp format
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json&callback=?', function (data) {
$('#weather').html('<p> Humidity: ' + data.current_condition.humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.current_condition.temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.current_condition.windspeedMiles + '</p>');
});

Try this :
$.getJSON('http://api.worldweatheronline.com/free/v1/weather.ashx?key=mykey&q=' + lat + ',' + longi + '&fx=no&format=json&callback=?', function (data) {
$('#weather').html('<p> Humidity: ' + data.data.current_condition[0].humidity + '</p>');
$('#weather').append('<p>Temp : ' + data.data.current_condition[0].temp_C + '</p>');
$('#weather').append('<p> Wind: ' + data.data.current_condition[0].windspeedMiles + '</p>');
});
because current_condition is an object array you can access it by using its index. addition data property because your JSON itself wrapped with data object.

Related

How do I display external API search results in a table?

I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}

How to return coordinates from a service in angularJS / cordova

I'm having trouble passing the data from my geolocationService to my weatherCtrl. I want to pass the position in my controller so I can send my openweather api's request.
Also, i have troubles understanding how is the data stored in services and how to use them correctly.
Here are my js files.
geolocationService.js
angular.module('app').service('geolocationService', function() {
geolocationSuccess = function(position){
alert(
'Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
return position;
}
geolocationError = function(error) {
alert(
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
this.getGeolocation = function(){
navigator.geolocation.getCurrentPosition(geolocationSuccess,geolocationError);
}});
weatherCtrl.js
angular.module('app').controller('weatherCtrl',['$scope', '$http', 'cityService', 'geolocationService',
function($scope, $http , cityService, geolocationService){
$scope.searchCity = function () {
var apiKey = "****";
var apiLang = "en"
var url = "http://api.openweathermap.org/data/2.5/forecast/daily?q="+$scope.city+"&APPID="+apiKey+"&units=metric&lang="+apiLang;
$http.get(url).success(httpSuccess).error(function(){
alert("Erreur : données non récupérées");
});
}
$scope.Math = Math;
httpSuccess = function(response){
$scope.weather = response;
}
$scope.setCity = function (city){
cityService.set(city);
}
$scope.geolocate = function (){
$scope.position = geolocationService.getGeolocation();
}
}
]);
So when I call geolocate(), the geolocationSuccess function is called but I don't know how to return the position correctly.
You return the position in your geolocationSuccess function, but didn't assign it to any variable.
because navigator.geolocation.getCurrentPosition is an async call.
ref: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition
so I do geolocationService.setGeolocation first, you can bind it to any other function, just be aware of async issue.
I add a Promise way to solve async issue, check the bottom.
weatherCtrl.js
app.controller('weatherCtrl', ['$scope', 'geolocationService',
function ($scope, geolocationService) {
geolocationService.setGeolocation();
$scope.geolocate = function () {
$scope.position = geolocationService.getGeolocation();
// now you can use $scope.position object.
console.log($scope.position);
}
}
]);
geolocationService.js
angular.module('app').service('geolocationService', function () {
var currentPosition = {};
geolocationSuccess = function (position) {
alert(
'Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
// set any properties you needs
currentPosition.latitude = position.coords.latitude;
currentPosition.longitude = position.coords.longitude;
// no need to return position here;
}
geolocationError = function (error) {
alert(
'code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
this.setGeolocation = function (position) {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}
this.getGeolocation = function () {
return currentPosition;
}
});
Deal with Async: Using Promise Approach:
weatherCtrl.js
app.controller('weatherCtrl', ['$scope', 'geolocationService',
function ($scope, geolocationService) {
$scope.geolocate = function () {
geolocationService.getGeolocation().then(pos => {
$scope.position = pos;
console.log($scope.position);
})
.catch(err => console.error(err));
}
}
]);
geolocationService.js
angular.module('app').service('geolocationService', function () {
this.getGeolocation = function () {
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(function (position) {
resolve(position);
}, function (error) {
reject(error);
});
})
}
});

Cordova geolocation plugin doesn't work on android

I'm using cordova ,geolocation plugin for showing latitude and longitude on android. There are plenty of question same as this so I read and tried their solution but couldn't fix the problem. The code below works perfectly on browser.
I tried 3 method, first: "navigator.geolocation.watchPosition" which returns wrong result(37.42,-122.08) in emulator(Android Studio) and doesn't return anything in device.
I also tried "navigator.geolocation.getCurrentPosition" with both "enableHighAccuracy" set 'true' and 'false' and I get timeOut error alerted.
When I delete deviceready, I don't get the timeOut, just wrong result from all three methods.
(function (window) {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var minAccuracyInMetres = 50;
var positionWatcher;
positionWatcher = navigator.geolocation.watchPosition(
geolocationSuccess2,
geolocationError2,
{ maximumAge: 0, timeout: 100000, enableHighAccuracy: true });
function geolocationSuccess2(position) {
// Reject if accuracy is not sufficient
if (position.coords.accuracy > minAccuracyInMetres) {
return;
}
// Only single position required so clear watcher
navigator.geolocation.clearWatch(positionWatcher);
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function geolocationError2(error) {
console.warn("Error while retrieving current position. " +
"Error code: " + error.code + ",Message: " + error.message);
}
//2
var onSuccess1 = function (position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
function onError1(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + 'highaccuracy: true');
}
var options1 = { maximumAge: 0, timeout: 300000, enableHighAccuracy: true };
navigator.geolocation.getCurrentPosition(onSuccess1, onError1, options1);
//3
var onSuccess = function (position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n')
};
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n' + ' high accuracy:false');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError, { enableHighAccuracy: false, timeout: 300 * 1000, maximumAge: 0 });
}
})(window);
I get the watchPosition part from another question in stackoverflow.
I use cordova version: 6.4.0.
I deleted the plugin and tried again but it didn't work.
the device I'm testing with is a lenovo tablet.
Thanks a lot.
UPDATE: my Geolocation version is: 2.4.0 Is it important???
After two days of struggling I turned on "High accuracy" in location settings. The app Works now!!!

Reload JSON data from javascript

I am trying to reload data every 5 seconds using jQuery. The URL for the JSON data can be found at http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json
This is the code I am trying:
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
One way to do it might look like this:
function getJson () {
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
}
var i = setInteval(getJson, 5000);

Display php data json_encoded with ajax

I convert my php code to json with json_encoded function.
After I write ajax code to display my data in ajax but when running don't display my data.
My json code:
[
{"Name":"fasher","Description":"2500 kg","Namyandegi":"20,500,000","Bazar":"22,410,000"}
,
{"Name":"shob","Description":"1000 kg","Namyandegi":"10,400,000","Bazar":"12,220,000"}
]
and ajax file:
<script type='text/javascript'>
$(document).ready(function(){
$.getJSON('saipa.php', function(data) {
$.each(data, function(key, val) {
$('ul').append('<li id="shoker">' + val.Name + ' ' + val.Description + ' ' + val.Namyandegi + ' ' + val.Bazar + '</li>');
});
});
});
</script>
<body>
<ul><li id="shoker"></li></ul>
</body>
Use the index overload $.each()
$.each(data, function(index) {
$('ul').append('<li id="shoker">' + data[index].Name + ' ' +
data[index].Description + ' ' +
data[index].Namyandegi + ' ' +
data[index].Bazar + '</li>'
);
});

Categories