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>
Related
this.responseText don't return the content of file. Can anyone help me with this problem? Thanks
Console.log don't return the content of file.
function loadMegaContent() {
var xhttp = new XMLHttpRequest();
var mesaj = "";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
mesaj = this.responseText
console.log("-WorkGood-" + this.responseText);
document.getElementById("logTextWXY").innerHTML = mesaj;
} else if (this.status == 404) {
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
};
xhttp.open("GET", "/admin/installstatus/fileContent.txt", true);
xhttp.send();
console.log("--mesaj" + mesaj);
}
Error
// The message display by console is next:
<title>Session expired</title>
<meta http-equiv="refresh" content="0;url=/Portal"/>
</head><body><p>Session expired please relogin</p></body></html>
If you just want to get the content of a file asynchronously, use fetch like:
async function loadMegaContent(){
let response = await fetch("/admin/installstatus/fileContent.txt");
if(response.status==200){
let data = await response.text();
console.log("-WorkGood-" + data);
document.getElementById("logTextWXY").innerHTML = data;
}else if (response.status==404){
mesaj = "The log don't exist in path";
document.getElementById("logTextWXY").innerHTML = mesaj;
}
}
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">
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>
I am fetching data from my database whith php and receive the response with ajax.
When I try to show all results, ajax reponse gives me all usernames combined as one long string back instead of an array which I can loop thru.
what am I missing?
my ajax code is per below:
function userquery(){
var user = document.getElementById("user").value;
var userq = "%"+user+"%";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
for(var i = 0; i < response.length ; i++){
document.getElementById("response").innerHTML += response["user"];
}
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("POST", "userquery.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("user=" + userq);
}
Your element is div so to separate each user and add it to new line. Add <br> at end. Change your code
document.getElementById("response").innerHTML += response["user"];
to
document.getElementById("response").innerHTML += response["user"]+"<br>";
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;