index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>API data</h2>
<input type="text" id="enter-city" placeholder="enter your city name" name="cityname">
<button id="btn1" onclick="getData()">Get Data</button>
<br>
<div id="w-data"></div>
<button id="btn2">Fetch Data</button>
<script src="prac.js"></script>
<!-- <script src="prac1.js"></script> -->
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</body>
</html>
Using Fetch :
var btn1 = document.getElementById("btn1");
function getData(){
var city = document.getElementById("enter-city").value;
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e2fddebba313bd6f70e2aa6127b2ce4c`)
.then((data) => {
return data.json()
}).then((data) => {
console.log(data)
document.getElementById("w-data").innerHTML =
`<ul>
<li>${data.name}</li>
<li>${data.main.temp}</li>
<li>${data.weather[0].description}</li>
</ul>
` });
document.getElementById("enter-city").value = "";
}
Using async await :
var btn1 = document.getElementById("btn1");
async function getData(){
var city = document.getElementById("enter-city").value;
var userData = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e2fddebba313bd6f70e2aa6127b2ce4c`)
const data = await userData.json();
console.log(data);
document.getElementById("w-data").innerHTML =
`<ul>
<li>${data.name}</li>
<li>${data.main.temp}</li>
<li>${data.weather[0].description}</li>
</ul>
`
document.getElementById("enter-city").value = "";
return data;
}
post - :
function postData() {
// console.log("started postData");
// url = "https://jsonplaceholder.typicode.com/posts"
// data = {
// title: 'foo',
// body: 'bar',
// userId: 1,
// }
// params = {
// method: 'post',
// headers: {
// "Content-type": "application/json"
// },
// body: JSON.stringify(data)
// }
// fetch(url, params)
// .then(response => {
// console.log("first then response: ", response)
// return response.json()
// })
// .then(data => {
// console.log("inside second then: ", data)
// console.log(data);
// console.log(data.title)
// console.log(data.userId)
// })
// .catch((error) => {
// console.log(error);
// })
// }
0 Comments