OpenWeatherMap Starting - javascript

I have just created an account with OpenWeatherMap
I want to get the current weather for location by City ID API Call:
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey
On my html page, how do I go about using this so that I can show my users what the weather is for the specific location?
I have used Yahoo Weather API, but want to try something different. Is the process similar? I don't see where I would call a callbackfunction like in yahoo weather api.
Do I have to write something like this?
<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>
I have tried this and it is not working.. and I couldn't find any examples on the website on how to integrate this into my html page.
Any help is appreciated.
UPDATE:
I have tried:
<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />
This uploads a black x.. not the picture of the current weather.
UPDATE:
I have found that I need to use ajax.. here is what I have so far:
<script>
$(document).ready(function () {
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id: '2172797', appid: 'myapikey' },
success: function (response) {
var dataArray = JSON.parse(response);
var weatherIcon = dataArray.weather.icon;
var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
document.getElementById('Weather-Image').src = iconUrl;
}
});
});
</script>

The data returned from http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey is described in the documentation of OpenWeatherMap.
You can't use it directly in a <script> or <img> tag as the response is JSON.
If you must use JavaScript to fetch the weather data, you will need AJAX (or any AJAX wrapper like $.ajax from jQuery) to call the API url then use JSON.parse to create an array with all the given data.
This is how it could look like:
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id : '2172797', appid: 'myAPIKey'},
success: function(response) {
// response from OpenWeatherMap
var dataArray = JSON.parse(response); // create an array from JSON element
}
});

Related

passing ajax data to backend javascript

I'm trying to log my users location using some Ajax code I was able to gather from online. I am trying to pass it to the backend code where I can store the data in my db for analytics. I have never used Ajax before and am not familiar with the syntax for passing through to backend.
Here's my code.
<div>Country: <span id="country"></span>
<div>State: <span id="state"></span>
<div>City: <span id="city"></span>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function (location) {
$("#country").html(location.country_name);
$("#state").html(location.state);
$("#city").html(location.city);
}
});
I basically need to pass $('#country').html(location.country_name); $('#state').html(location.state); $('#city').html(location.city); to my nodejs code. I've used fetch before in js but not sure if thats the syntax to include the Ajax code in it. Appreciate the help.
If you have some data to be sent to the server using AJAX and if you have something like the HTML that you have got, you can very well use the textContent or .text() (using jQuery) of the element. Here's how you do it.
// Sending data to the server...
var data = {
country: $("#country").text(),
state: $("#state").text(),
city: $("#city").text()
};
console.log("Data to be sent!");
console.log(data);
console.log("Serialised data!");
console.log($.param(data));
// Send data to end point and get JSON value.
$.getJSON("/endpoint?" + $.param(data), function (res) {
console.log(res);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Country: <span id="country">India</span>
<div>State: <span id="state">Tamil Nadu</span>
<div>City: <span id="city">Chennai</span>
In the above example, the contents of the HTML will be sent to the server. Check out the console and network for what is been sent.
Here's from the Network tab of Google Chrome:
To anyone who else who is looking at this question, you may also use javascript within the Ajax function. It may not be the proper way, but it does work.
<script>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function( location ) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
console.log(location)
var locaionValues = location;
var countryNameLocation = location.country_name;
var stateNameLocation = location.state;
var cityNameLocation = location.city;
fetch('/locationTracker', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
locaionValues,
countryNameLocation,
stateNameLocation,
cityNameLocation,
})
})
}
});
this works great, and in my nodejs code, I am logging the code like so:
app.post('/locationTracker', (req, res) => {
var country = req.body.countryNameLocation
var state = req.body.stateNameLocation
var city = req.body.cityNameLocation
console.log("country is " + country)
console.log("state is " + state)
console.log("city is " + city)

Render some HTML tag from another web application

I want to render some value of span element from internal website to my website by GET / FETCH request or by another alternative.
This is my current code but actually IDK what to do, I've managed to receive some un-useful data and not the data I need, and even this data was the expected data, I want to render only the span value from there.
async function uiTagChecking() {
$.ajax({
url: url,
success: function(data){
console.log(data);
const curSpan = document.getElementById(data);
}
});
}
Technical info:
Node JS
JavaScript
HTML + CSS
success: function(data){
console.log(data);
const curSpan = document.getElementById(data);
curSpan.innerHTML = data;
}

Extract data from current URL and use it in ajax call as a paramenter

I am developing a website in which only 1 html page is there in which I first fethch the url & gets the id from url and send it to api using ajax call. On success, I displays data of the given id from url.My code is as-
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#main').hide();
var url = window.location.href;
var formno = url.substr(url.lastIndexOf('/') + 1);
if (formno != 'Login.html') {
var apiUrl = 'http://localhost:801/api/api/Patient/Get';
$.ajax({
url: apiUrl,
crossDomain: true,
contentType: "application/json",
type: 'GET',
data: { formNo: formno },
success: function (result) {
$('#main').show();
alert("Success" + result)
},
error: function (result) {
alert("error :: " + JSON.stringify(result))
}
});
}
});
</script>
when I use the url as abc.in#1 it displays the success alert but I want to give the url in format abc.in/1 at that time it gives
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Why it can not find the page? Is there any solution for this?
I want to give plain url as abc.in/1 where 1 is id and which is dynamic.
Is there any solution?
Your browser is probably trying to access document on location abc.in/1, which doesn't exist. You will need some server side logic for this, e.g. php router which will always serve your document, and additonal parameters will be processed by it. abc.in#1 anchor is different type of url parameter, which purpose is to be processed by document or javascript on client side.

Can't read JSON data correctly by $.each jquery

I am trying to use $.getJSON to get data from the NHTSA recall API and append the Component object from the Results array to a div with the id="data". Here is the URL I am trying to get JSON for:
http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json
Here is the snippet that I am using:
`var url = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.getJSON( url, function(data) {
console.log(data.Results);
$.each(data.Results, function(i,Results){
var component = this.Component;
$('#data').append('<h4>' +component+ '</h4>');
}
}
I have used this similar format for a few other API's and it worked so I am not sure why the call isn't going through.
I ran into a cross origin request problem using $.getJSON (as I often do), so I tried jsonp and succeeded. Please give it a try and let me know if you have questions.
$(document).ready(function() {
var http = 'http://www.nhtsa.gov/webapi/api/Recalls/vehicle/modelyear/2000/make/honda/model/accord?format=json';
$.ajax({
url: http,
dataType: 'jsonp',
jsonpCallback: "callback",
type: "GET",
success: function (data) {
var div = $('#data');
for(var i = 0; i < data.Results.length; i++) {
$(div).append('<div>' + data.Results[i].Component + '</div>');
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>

Using javascript to access Google's URL shortener APIs in a Google Chrome extension

I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.
I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)
I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.
My javascript file currently looks like this:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.
The code will look something like this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
Here is the jquery ajax api
Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.
I wrote a blog post with a simple solution:
http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html
It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
var request = gapi.client.urlshortener.url.insert({
resource: {
longUrl: 'http://your-long-url.com'
}
});
request.execute(function(response) {
var shortUrl = response.id;
console.log('short url:', shortUrl);
});
};
var googleApiLoaded = function() {
gapi.client.load("urlshortener", "v1", shortenUrl);
};
window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
Here I will explain how to create a google url shortener automatically on every web page using javascript and html
Phase-stages are
1) Make sure you have a jquery script code, if there is already advanced to phase two.
2) Add the following script code, after or below the jquery script code:
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
3) How to use it:
If you want to use html tags hyperlink
<a id="apireadHref" href="blank">blank</a>
If you want to use html tag input
<input id="apireadValue" value="blank"/>
The end result
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
HTML
<a id="apireadHref" href="blank">blank</a>
or
<input id="apireadValue" value="blank"/>
DEMO
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "longUrl": "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
Worked out a quick and simple solution on this issue. Hope it will solve the problem.
<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
gapi.client.setApiKey('[GOOGLE API KEY]');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("result").innerHTML = "";
var Url = "http://onlineinvite.in";
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': Url
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + Url + "<br>";
str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("result").innerHTML = str;
}
else {
alert("Error: creating short url \n" + response.error);
}
});
});
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>
Need to replace [GOOGLE API KEY] with the correct Key
Your LongUrl should replace Url value i.e. http://example.com

Categories

Resources