I'm currently working on a weather site. I want to get the user input into a variable that changes the current city. Hope someone of you can help me.
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
}
window.onload = function() {
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
location is getting updated after hitting the submit button. But the value of the variable doesn't change. I've already looked around stackoverflow and other sites but didn't find any solution that works for me.
1st : Your request will only run on page load . you need to run that again after user change the userInput .so make it as a function and call it every time of userInput change like this .
var userInput = "London";
function changeValue() {
userInput = document.getElementById("user_Input").value;
document.getElementById("location").innerHTML = document.getElementById("user_Input").value;
ajax_call();
}
function ajax_call(){
var api = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
var units = "&units=metric";
var url2 = api + userInput + units + APPID;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
var iconCode = myObj.list[0].weather[0].id;
var directions = myObj.list[0].deg;
for (var i = 0; i < 7; i++) {
document.getElementById("day" + i).innerHTML = Math.round(myObj.list[i].temp.day) + "°";
document.getElementById("icon" + i).src = "sl_line/" + iconCode + ".svg";
document.getElementById("wota" + i).innerHTML = wochentag[day.getDay()+i+1];
document.getElementById("humidity").innerHTML = Math.round(myObj.list[0].humidity);
document.getElementById("wind").innerHTML = myObj.list[0].speed + " m/s";
document.getElementById("direction").innerHTML = directions;
}
}
};
xmlhttp.open("GET", url2, true);
xmlhttp.send();
}
window.onload = function() {
ajax_call();
};
<article>
<input id="user_Input" type="text" placeholder="Ortsuchen...">
<button id="submit" onclick="changeValue()">Submit</button>
<span id="location">Unknown</span>
</article>
<section>
<div>
<div><span id="day0" class="ml:.25r fs:6r">0</span></div>
<div><span id="wochentage">0</span></div>
</div>
<div>
<img id="icon0">
</div>
<div>
<span id="wind">0</span><span id="direction"></span><span></span>
</div>
<div>
<span id="humidity">0</span><span>%</span>
</div>
</section>
Related
I want to prevent user from predicting the target script (test.php) AND do the whole "counter" logic on the server side.
I don't know how to achieve it with PHP.
I would like to open the file from the server side with PHP so the client will not have the possibility to see and know what file will open after 15 clicks. Because by typing the URL of the file it is possible to open it even before 15 clicks.
Thanks
HTML
<div id='overlay' class='overlay'></div>
<div class="view" id="view"></div>
<div class="canvas">
<div id="totalCounter" class="total-counter"></div>
<button id="clap" class="clap-container" tabindex="-1"></button>
<div id="clicker" class="click-counter">
<span class="counter"></span>
</div>
</div>
JAVASCRIPT
let accCounter = 0;
let totalCount = 0;
document.getElementById('totalCounter').innerText = totalCount;
document.getElementById('clap').onclick = function() {
const clap = document.getElementById('clap');
const clickCounter = document.getElementById("clicker");
upClickCounter();
loadDoc();
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter ++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("view").innerHTML = this.responseText;
}
};
xhttp.open("GET", "clickcheck.php", true);
xhttp.send();
document.getElementById("view").style.visibility="visible";
if (totalCount + accCounter%15) {
document.getElementById('view').style.visibility="hidden";
}
document.getElementById('overlay').style.display = 'block';
if (totalCount + accCounter%15) {
document.getElementById('overlay').style.display = 'none';
}
}
clickcheck.php:
<?php
session_start();
if (!array_key_exists('clickcount', $_SESSION)) {
$_SESSION['clickcount'] = 1;
}
if ($_SESSION['clickcount'] < 15) {
header('HTTP/1.1 404 Not found');
exit();
} else {
include("test.php");
}
?>
I am calling a function using onClick inside button. The called function is inside an object and it is getting called each second using setTimeout. But callback function is not getting called by setTimeout and works for just first call.
if i do not use object and use a encapsulating function that returns startPomadoro function, then its working.
###HTML Code ##########
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
### JS COde
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText:'',
startPomodoro: function(){
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if(this.countPomadoro<pomadoroTimeInMinutes){
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
this.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
this.countPomadoro++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
if(this.countBreak<breakInMnutes){
var minutesLeftBreak = this.breakInMinutes - this.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
this.countBreak++;
this.displayPomadoro();
setTimeout(this.startPomodoro, 1000);
}
else {
this.currentTimerText=" Break Time is UP. ";
this.displayPomadoro();
}
}
},
displayPomadoro: function(){
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent=this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
You had a problem with this not being what you think, when function was called from setTimeout. Try something like this:
var pomodoroClock = {
countPomadoro: 0,
countBreak: 0,
currentTimerText: '',
startPomodoro: function() {
var that = this;
var pomadoroTimeInMinutes = document.getElementById('pomodoroInput').value;
var breakInMinutes = document.getElementById('breakInput').value;
if (this.countPomadoro < pomadoroTimeInMinutes) {
var minutesLeftPomadoro = pomadoroTimeInMinutes - this.countPomadoro;
that.currentTimerText = "Your have " + minutesLeftPomadoro + " Minutes Left.";
that.countPomadoro++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
if (that.countBreak < breakInMinutes) {
var minutesLeftBreak = that.breakInMinutes - that.countBreak;
currentTimerText = "Your have " + minutesLeftBreak + " Minutes Left in Break.";
that.countBreak++;
that.displayPomadoro();
setTimeout(function() { that.startPomodoro() }, 1000);
} else {
that.currentTimerText = " Break Time is UP. ";
that.displayPomadoro();
}
}
},
displayPomadoro: function() {
var pomodoroHtmlElement = document.createElement('p');
var outputDiv = document.getElementById('output');
pomodoroHtmlElement.textContent = this.currentTimerText;
outputDiv.appendChild(pomodoroHtmlElement);
}
}
<div class="cold-md-12 text-center">
<button>Set Pomodoro</button>
<input id="pomodoroInput" type="number">
<button>Set Break</button>
<input id="breakInput" type="number">
</div>
<div class="cold-md-12 text-center"><br>
<button onClick="pomodoroClock.startPomodoro()">Start Pomodoro</button>
</div>
<div id="output">
</div>
PS. You also had a typo breakInMnutes instead of breakInMinutes.
I have solved this problem by moving away from jquery , and simply
setting event handler on divs by wrapping each image inside one div using
JavaScript. Below is the sample code.
//code
handler.divs.forEach(function(div){
var img = document.getElementById(div);
img.onclick = function(){
var id = parseInt(img.id,10);
userPattern.push(id);
handler.effect(id);
console.log(" div clicked " + id + " u p " + userPattern);
if(userPattern.indexOf(id) !== simonGame.PATTERN.indexOf(id)){
console.log(" if ");
handleWrongInput();
} else if(userPattern.length === simonGame.PATTERN.length){
setTimeout(function(){simonGame.patternGen({result:"success"})},1200);
}
}
});
console.log(" up " + userPattern + " SGP " + simonGame.PATTERN);
I'm trying to use JavaScript to display data from an XML file. My data isn't being displayed to the web page and I'm not sure why.
Any help/advice would be appreciated. My code is displayed below.
NOTE - I have no experience with XML so be aware that I am completely new to it.
<script>
var xmlData;
function loadXml () {
var filename = "CDLibrary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml () {
var CdElements;
var CdTitle;
var count;
CdElements = xmlData.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml();">
</div>
</body>
<html>
<head><title>Import XML Data</title></head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml()">
</div>
<script>
var xmlData;
function loadXml () {
var filename = "CDLibary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml(xmlDataBase) {
var CdElements;
var CdTitle;
var count;
CdElements = xmlDataBase.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</body>
</html>
You're not using the var xmlData instead you're using a var xmlDataBase. Replace you code to:
CdElements = xmlData.getElementsByTagName("CD");
And since you're using a global var xmlData, it's available inside displayXml function, in this case no need for function displayXml(xmlDataBase) if you use function displayXml() it'll be enough.
Using the w3schools link and changing some information and changing the directory I got it working. There must be an error in the template i was following, thank you all for your time and efforts.
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "CDLibrary.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("performer")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I ve got nothing in console. It should change contain of html to the information taken from openweatherapp for this zip code(i check this zip and it exists and function updateByZip creates good link). First code is JS and second HTML.
JS
var temp;
var loc;
var humidity;
var icon;
function bg() {
var backs = ["http://wallpapercave.com/wp/JthAGYd.jpg", "http://www.desktopwallpaperhd.net/wallpapers/20/b/welshdragon-landscapes-cometh-background-204971.jpg", "http://s1.picswalls.com/wallpapers/2014/08/08/scottish-landscape-desktop-backgrounds_015751372_152.jpg", "http://img.wallpaperfolder.com/f/4313075B95B2/amazing-winter-backgrounds-6770538-landscape.jpg"];
var ran = Math.floor(Math.random() * (backs.length));
$('body').css("background-image", "url('" + backs[ran] + "')")
//document.body.style.background = "url/'('" + backs[0] + "') no-repeat";
}
function tempCF() {
var x = document.getElementById("temp").innerHTML;
var y = document.getElementById("CF").innerHTML;
x = parseInt(x);
if (y == "C") {
x = Math.floor((9 / 5 * x + 32));
document.getElementById("temp").innerHTML = x;
document.getElementById("CF").innerHTML = "F"
} else if (y == "F") {
x = Math.floor((x - 32) * 5 / 9);
document.getElementById("temp").innerHTML = x;
document.getElementById("CF").innerHTML = "C";
};
}
function updateByZip(zip) {
var APPID = "55e568aa04114cdf3dc4b90c9ae0a60c";
var url = "api.openweathermap.org/data/2.5/weather?zip=" + zip + "&APPID=" + APPID;
sendRequest(url);
}
function sendRequest(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
weather.temp = data.main.temp;
weather.humidity = data.main.pressure;
weather.loc = data.name;
//weather.icon = data.weather[0].id;
update(weather);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function update(weather) {
document.getElementById("temp").innerHTML = weather.temp;
document.getElementById("humidity").innerHTML = weather.humidity;
document.getElementById("loc").innerHTML = weather.loc;
//document.getElementById("icon").innerHTML = weather.icon;
};
window.onload = function() {
var temp = document.getElementById("temp").innerHTML;
var loc = document.getElementById("loc").innerHTML;
var humidity = document.getElementById("humidity").innerHTML;
//var icon = document.getElementById("icon").innerHTML;
updateByZip(94040);
//weather.icon = "https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png";
};
HTML
<head>
<link href="https://fonts.googleapis.com/css?family=Poiret+One" rel="stylesheet">
</head>
<body onclick="bg()">
<div class="container-fluid">
<div class="wrapper">
<div class="row">
<div class="title"><span id="loc"> Your location</span></div>
</div>
<div class="row">
<div class="col-ms-4">
<div class="fircol"><span id="temp">0</span>°<span onclick="tempCF()" id="CF">C</span></div>
</div>
<div class="col-ms-4">
<div class="seccol"><span id="humidity">Rain</span></div>
</div>
<div class="col-ms-4">
<div class="thicol"><span class="icon"><img src= https://cdn1.iconfinder.com/data/icons/hawcons/32/700175-icon-1-cloud-128.png></img></span></div>
</div>
</div>
</div>
</div>
</body>
Your API url is not correct.
You should write:
var url = "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + "&APPID=" + APPID;
I am just trying to prototype a simple functionality using javascript for learning purpose, but the contents within the <p> tag are not updating and I am stuck at this point. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title> Ajax Search Box </title>
<script>
function LoadList()
{
var searchBox = document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
var xHttp = new XMLHttpRequest();
searchedChars += searchBox.value;
xHttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
var xmlContent = this.responseXML;
var nameList = xmlContent.getElementsByTagName("name");
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i].textContent + "<br/>";
}
resultBox.innerHtml = dispText;
}
};
xHttp.open("GET","AssessorList.xml",true);
xHttp.send();
}
</script>
</head>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">
No Data Available.
</p>
</body>
</html>
Could someone tell me why the innerHtml is not updating? Thanks in advance.
P.S: The code is fetching the data from the xml file as I could see in browser's console, the values being passed to the dispText variable.
<!DOCTYPE html>
<html>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">No data available</p>
<script>
function LoadList() {
var xhttp = new
XMLHttpRequest();
var searchBox =
document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
searchedChars += searchBox.value;
xhttp.onreadystatechange = function() {
//alert(this.status);
if (this.readyState == 4 && this.status == 200) {
var xmlContent = this.responseXML;
var nameList = searchedChars;
alert(nameList);
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i] + "<br/>";
}
resultBox.innerHTML = dispText;
}
};
xhttp.open("GET", "ajax.txt", true);
xhttp.send();
} </script>
</body>
</html>
Hope this may help you