I am trying to get weather information from openweather.com api with the help of geo-location (lattitude and longitude). I can not get it why it is not getting data. Here is my code:
function getWeather(lat, long){
console.log(lat +" "+ long); //23.8008983 90.3541741
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
$("#weather").value(temp);
});
I try to print "Successfully data recieved" in console but it does not print. I assume the callback is not happening. it is confirmed that function calling (getWeather()) is okay as I am getting values of latitude and longitude (I kept those values in comment). I badly need your help. I manually typed the url with latitude and longitude in browser, it returned me the expected output that I should get from this JSON call. But not working in code.
I messed with this for a bit and the realized that sometimes it's the simplest solution... try requesting the secure (https) URL:
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8", function(json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
$("#weather").value(temp);
});
Your function is not properly closed, you missed ending } brace (I guess it is a typo). I've tried your code and it works for me like a charm. Also Be sure your `jquery library is included perfectly.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
(function() {
getWeather(23.8008983,90.3541741);
})();
function getWeather(lat, long){
var watherAPI = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"&units=imperial&APPID=7a26948f2294e4d5754c951a6aaf7cf8";
$.getJSON( watherAPI, function (json) {
console.log("Successfully data recieved");
var temp = Math.round(json.main.temp);
console.log(temp);
})}
</script>
</body>
</html>
Related
First thing I am new to javascript.
What I am trying to do is to get data from a URL in json and save it in java script variable.
What I have already done:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
This shows me output : 1
and what I want is to get data from URL like:
var json ='url';
obj = JSON.parse(json);
alert(obj.count);
and for the clearance I am using this URL to get JSON data and i just need to print fare from the data.
any help in this matter would be highly appreciated !!
I have done this in php like this way, but I need it to do this in javascript.
$jsonData = file_get_contents("url");
$json = json_decode($jsonData,true);
echo $json['fare'];
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
console.log(data)
});
Try this ways to read ur URL
Try this way, convert the url to an array then
var json = 'data url in array',
obj = JSON.stringify(json);
alert(obj.count);
Use Ajax call for fetching data from external sources.
On clicking it will fetch data from the url.
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://daewoocab-test.herokuapp.com/api/v1/rates?token=6ab676ddd7bf00101408ea3a27fdbb8ad22e9dcdf2faafdcd2ef0efc1509d463&pickup_area=Street%201%2CF-8%2CIslamabad%2CIslamabad%20Capital%20Territory%2CPakistan&drop_area=padhrarazadari.com%2C%20kallar%20kahar%20road%2C%20padhrar%2C%20punjab%2C%20pakistan&distance=169", function(result){
console.log(result);
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<button onclick="showHint()">abcd</button>
<script>
function showHint() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(JSON.parse(xhttp.response));
}
};
xhttp.open("GET", "http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", true);
xhttp.send();
}
</script>
</body>
</html>
Temporary Solution:
Here is my working fiddle
If you get 'Access-Control-Allow-Origin' header is present on the requested resource. error, add CORS extension to your browser and enable it.
hope this helps :)
The following is a JavaScript file that searches through YouTube video data using its API. Down at the bottom you'll see the onSearchResponse() function, which calls showResponse(), which in turn displays the search results.
As this code from Codecademy stands, a HUGE amount of information gets printed relating to my search term.
Instead of all that, can I simply display a hyperlink using the title and videoId attributes? How would I go about altering responseString in showResponse() to build that link? Thank you!
// Your use of the YouTube API must comply with the Terms of Service:
// https://developers.google.com/youtube/terms
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See link to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: 'clapton'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
console.log(response);
}
Here is the corresponding HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="stylesheets/styles.css">
<meta charset="UTF-8">
<title>My YouTube API Demo</title>
</head>
<body>
<section>
<div id="response"></div>
</section>
<script src="javascripts/search-2.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</body>
</html>
Your advice is much appreciated!
I think it might be what you are exactly trying to do.
function showResponse(response) {
var html = response.items.map(itemToHtml);
document.getElementById('response').innerHTML += html;
}
function itemToHtml(item) {
var title = item.snippet.title;
var vid = item.id.videoId;
return generateHyperlink(title, vid);
}
function generateHyperlink(title, vid) {
return '' + title + '<br/>';
}
This code show up links named title having YouTube video link using videoId.
I'm doing the FreeCodeCamp course and i'm trying to build a weather app. I found a nice tutorial on how to get the latitude and longitude with geolocation. But now when I try and run the app it doesn't seem to be retrieving the ajax data for me to parse through. I was trying locally and moved it to hosting thinking that might have been it but now I just get a weird error on line one of my html and i don't see anything wrong. Thanks guy here is the code and it's live on weatherapp.boomersplayground.com
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Weather APP</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src='script.js'></script>
</head>
<body>
<div id="forecast">
<h1>Weather at <span id="location"> </span></h1>
<!-- <div id="imgdiv">
<img id="img" src=""/> -->
</div>
<p>It is currently <span id="temp"> </span>F with <span id="desc"> </span></p>
<p>Wind: <span id="wind"></span></p>
</div>
</body>
</html>
script.js
$(document).ready(function(){
var Geo = {};
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(success,error);
} else {
alert('Geolocation is not supported');
}
function error(){
alert("That's weird! We couldn't find you!");
}
function success(position){
Geo.lat = position.coords.latitude;
Geo.lng = position.coords.longitude;
}
var key = 'c7e3b3ac66e765aa';
var Weather = "http://api.wunderground.com/api/"+ key +"/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json";
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
}
})
//setting the spans to the correct parameters
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
// filling the image src attribute with the image url
// $('#img').attr('src', img);
});
You use the variables initialised at the AJAX response outside of the success callback. You should use them inside the callback, since they're created asynchronously:
$.ajax({
url : Weather,
dataType : 'jsonp',
success : function(data) {
var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
}
});
Because you are treating an Asynchronous call as a synchronous one. The Ajax call needs to be in the success callback of getCurrentPosition. You are building the Ajax url before the at and lng is returned.
I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>
This code is working on other test environment but not on mine.
Do you know why?
I am using Amazon EC2 and Cotendo CDN.
The result I am getting is a blank page.
Thanks in advance!
<html>
<head>
<title>Geo Test</title>
<script type='text/javascript' src='http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
console.log(data);
var c = data.countryCode;
if(c=="US" || c=="US" ){
document.getElementById('ddd').innerHTML = 'US'; } else {
document.getElementById('ddd').innerHTML = 'Not US';}
/*
this service needs ip
var ip = data.host;
alert(ip);
$.getJSON( "http://freegeoip.net/json/"+ip,
function(data){
console.log(data);
}
);*/
}
);
});?
</script>
</head>
<body>
<div id="ddd"></div>
</body>
</html>
Change this line:
$(document).ready( function() {
to that:
jQuery(document).ready( function($) {
It's necessary, because inside http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1 you've already got a call of jQuery.noConflict(); , so jQuery is not accessible by using the $
...and also remove the ? (see Pointy's comment above)