I have a form where user types in the city name, I want to make an API call and get weather results in that city and then display it in the console.
I'm getting an error because for some reason the variable that holds input.value is not being concatenated into the string.
Here's the code:
var request;
var input1 = document.getElementById('city');
var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
var apikey = '&APPID=433b12b793d7ebc17989745c069a540b';
var sum = api + input1.value + apikey;
function myFunction() {
request = new XMLHttpRequest();
request.open('GET', sum, true);
request.onload = function() {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
console.log(data);
} else {
console.log(input1.value);
}
}
request.send();
}
myFunction(input1.value);
<input id='city' value='San Francisco'>
Thanks for any help!
Your code is ok, you just need to put everything inside the function.
<script>
function myFunction() {
var request;
var input1 = document.getElementById('city');
var api = 'https://api.openweathermap.org/data/2.5/weather?q=';
var apikey =
'&APPID=433b12b793d7ebc17989745c069a540b';
var sum = api + input1.value + apikey;
request = new XMLHttpRequest();
request.open('GET', sum, true);
request.onload = function () {
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
console.log(data);
} else {
console.log(input1.value);
}
}
request.send();
}
</script>
Related
The app that I'm working on does not respond with the API address. I only get the ajax responding, but not the weather api that I'm trying to call.
I've tried everything that I could think of with my current knowledge.
let search = document.getElementById("search-bar");
let temp = document.getElementById("temperature");
let input = document.getElementById("input");
let city = document.getElementById("city");
const key = "";
input.addEventListener("keyup", enter);
function enter(event) {
if (event.key==="Enter") {
details();
}
}
function details() {
if (searchInput.value === ""){
} else {
let searchLink = "https://api.openweathermap.org/data/2.5/weather?q={}" + searchInput.value + "&appid=" + key;
httpRequestAsync(searchLink, talk)
}
}
function talk(talking){
let jsonObject = JSON.parse(talking);
city.innerHTML = jsonOject.name;
temp.innerHTML = parseInt(parseInt(jsonObject.main.temp - 273) + "°");
}
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
request.open("GET", url, true); // true for asynchronous
request.send();
}
The expected outcome should be the weather api being called and displayed information in the console.
Try replacing last function with this:
function httpRequestAsync(url,callback){
var httpRequest=new XMLHttpRequest();
httpRequest.onreadystatechange = () => {
if (httpRequest.readyState == 4 && httpRequest.status == 200)
callback(httpRequest.responseText);
}
httpRequest.open("GET", url, true); // true for asynchronous
httpRequest.send();
}
I just corrected variable naming
I am trying to build a simple code where I fetch some JSON data (weather information) and log the temperature to the console. HEre is my sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Weather Application</title>
</head>
<body>
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=65a3719d36e2d698392212cd888b5ccf', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data => {
console.log(main.temp)
}
} else {
console.log('error')
}
}
request.send()
</script>
</body>
</html>
I get the prompt to enter the city name and the value is saved to the variable properly. However, my console is not logging the temperature.
Here is a sample of the JSON response:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":300,
"main":"Drizzle",
"description":"light intensity drizzle",
"icon":"09d"
}
],
"base":"stations",
"main":{
"temp":280.32,
"pressure":1012,
"humidity":81,
"temp_min":279.15,
"temp_max":281.15
},
"visibility":10000,
"wind":{
"speed":4.1,
"deg":80
},
"clouds":{
"all":90
},
"dt":1485789600,
"sys":{
"type":1,
"id":5091,
"message":0.0103,
"country":"GB",
"sunrise":1485762037,
"sunset":1485794875
},
"id":2643743,
"name":"London",
"cod":200
}
Any idea what I might be doing wrong?
Thanks in advance for the help.
I have already searched for several code examples on how to do it.
I would like to have the console logging the temperature.
Also, does anyone knows how to convert the temperature from Kelvin to Celsius?
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=65a3719d36e2d698392212cd888b5ccf`, true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
// kelvin to celsius formula is celsius = Kelvin - 273.15
console.log(`${data.main.temp - 273.15}C`)
} else {
console.log('error')
}
}
request.send()
</script>
There is no property temp on the base object - it is in the nested data object:
console.log(data.main.temp);
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=65a3719d36e2d698392212cd888b5ccf', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
((main)=>{
console.log(main.temp)
})(data.main)
} else {
console.log('error')
}
}
request.send()
</script>
<script>
var cityName = prompt("Please enter city name", "London");
var request = new XMLHttpRequest()
request.open('GET', 'https://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&appid=65a3719d36e2d698392212cd888b5ccf', true)
request.onload = function() {
// Begin accessing JSON data here
if (request.status == 200) {
var data = JSON.parse(this.responseText);
let temperature = data.main.temp - 273.15;
console.log(temperature);
} else {
console.log('error')
}
}
request.send()
</script>
I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">
Hi guys this script gets the data from my arduino.
<script>
var nivel = 0;
var data_val = 0;
function GetArduinoInputs()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
document.getElementById("input3").innerHTML = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
data_val = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
}
}
}
}
request.open("GET", "ajax_inputs" + nocache, true);
request.send(null);
setTimeout('GetArduinoInputs()', 200);
}
</script>
But I am not able to read the value of data_val on my other script:
<script>
var level = data_val;
</script>
Can someone help my out, please
You could use the same approach that you are using to store the value that you get from the server in the local HTML to retrieve the value in the "other script".
//from the "other script"
var level = document.getElementById("input3").innerHTML;
I want to open link example.com/id= with a different ids every 5 second using JS/jQuery.
I tried this:
<script type='text/javascript'>
setInterval(function() {
var i = 1;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com?id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
</script>
but this is not working for me.
What should I do?
Since you've tagged it with jquery, here is one way:
$(function() {
var id = 1;
setInterval(function(){
$.get("example.com", { id: id }, function(data) {
console.log(data);
id++;
})
.fail(function(xhr, status, error) {
console.log("XHR:: " + xhr + " | Status:: " + status + " | Error:: " + error);
});
}, 5000);
});
You're using local variable i, so for every interval, this variable is reset to its initial value 1. Try using global variable instead of local:
var i = 1;
setInterval(function() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com/id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
or to avoid putting variable into global scope. You could wrap your function inside an immediate function. Like this:
(function(){
var i = 1;
setInterval(function() {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
var add = 'example.com/id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
}, 5000);
})();
DEMO
You have to specify the declaration of i var i=1;outside the setInterval()
Try this
code
var i = 1;
self.setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
alert(request.responseText); // alert response
}
}
var add = 'example.com?id='+i;
request.open('GET', add, true);
i = i + 1;
request.send();
},5000);
Hope this helps,thank you