Cannot call method 'getElementsByTagName' of null - javascript

This is my first AJAX and my first use of .php file. I'm following an exercise in the text and it's not working. I tried to use the alert function as many times as possible to check what is feeding in to variables and functions, but I'm really unsure what's going on in the background. I checked the Yahoo! Weather RSS feed which is supposed to give this website some information ("http://weather.yahooapis.com/forecastrss?p=94558") and I do see the "item" tag. The console keeps saying "Cannot call method 'getElementsByTagName"!! Appreciate any input in advance....
<!DOCTYPE html PUBLIC "-\\W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Weather Report</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<style type="text/css">
html {
height: 100%;
margin: 0;
padding: 0;
}
body
{
height: 100%;
margin: 0;
padding: 0;
}
a { color: #91c056; }
a:link { color: #515151; text-decoration: none; }
a:visited { color: #515151; text-decoration: none; }
a.back:hover { color: #6eece3; }
#content-pane{
font-family: Courier New, monospace;
letter-spacing: -0.05em;
font-size: 15px;
line-height: 23px;
float:left;
width:100%;
padding-left: 5%;
padding-top: 5%;
}
#headline
{
font-family: Helvetica, "Helvetica Neue", Arial, sans-serif;
font-weight: bold;
letter-spacing: -0.05em;
font-size: 60px;
line-height: 60px;
color: #323232;
text-align: left;
}
</style>
<script type="text/javascript">
/* <![CDATA[ */
var weatherRequest = false;
function getRequestObject(){
try {
httpRequest = new XMLHttpRequest();
}
catch (requestError){
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (requestError) {
try{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (requestError){
window.alert("Your browser does not support AJAX!");
return false;
}
}
}
return httpRequest;
}
function weatherUpdate(){
if(!weatherRequest)
weatherRequest = getRequestObject();
var zip = document.forms[0].zip.value;
weatherRequest.abort();
weatherRequest.open("get", "WeatherReport.php?zip=" + zip, true);
weatherRequest.send(null);
weatherRequest.onreadystatechange=fillWeatherInfo;
}
function fillWeatherInfo(){
if (weatherRequest.readyState == 4 && weatherRequest.status == 200){
var weather = weatherRequest.responseXML;
var weatherItems=weather.getElementsByTagName("item");
if (weatherItems.length > 0){
for (var i=0; i<weatherItems.length; ++i){
var curHeadline = weatherItems[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
var curLink = weatherItems[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
var curPubDate = weatherItems[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;
var curDesc = weatherItems[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
var weatherSpot = document.getElementById('weatherPara');
var curStory = "<a href='" + curLink + "'>" + curHeadline + "</a><br />";
curStory += "<span style='color: gray'>";
curStory += curDesc + "<br />";
weatherSpot.innerHTML = curStory;
}
}
else
window.alert("Invalid ZIP code.");
}
}
/* }]> */
</script>
</head>
<body onload ="weatherUpdate()">
<div id="content-pane">
go back
<div id="headline">Weather Report</div>
<br />
<br />
<br />
<br />
<form method="get" action="">
<p>ZIP code <input type="text" name="zip" value="94558"/> <input type="button" value="Check Weather" onclick="weatherUpdate()" /></p>
</form>
<p id="weatherPara"></p>
</div>
</body>
</html>
Below is the WeatherReport.php file.
<?php
$Zip = $_GET["zip"];
$WeatherURL
= "http://weather.yahooapis.com/forecastrss?p=" . $Zip;
header("Content-Type: text/xml");
header("Content-Length: " . strlen(file_get_contents($WeatherURL)));
header("Cache-Control: no-cache");
readfile($WeatherURL);
?>

Try adding your WeatherReport.php in form action. You have to specify your php file in you action otherwise the form will point to the same file.

In your function fillWeatherInfo, you haven't passed it any parameters. Therefore, I believe weatherRequest.responseXML is an empty object.
In your onreadystatechange property, you need to pass in the parameters of the AJAX response to the handler.

Related

How to add bg image to API weather project?

Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!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>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly

How to reload page without losing any data

I am pretty new to web development and I am making this little project that consists in a little site that allows a user to add and remove their goals(kinda like a to do list)
I want to implement a last feature that allows the browser to save the content of the page, so that if the user reloads the page, he/she does not lose track of their goals. I tried using local storage but it's not working.
Any suggestion/tips on how to tackle such problem?
Thank you very much and I apologise, in advance for the code smell.
var i = 0
var j =0
var parentElement = document.getElementById('new-goals')
function addGoal(){
var userGoal = window.prompt('Enter goal: ')
var divTag = document.createElement('div')
divTag.className = 'goalsSection'
divTag.id = 'goal- ' + i
i++
var goal = document.createElement('p')
goal.innerHTML = userGoal
goal.className= 'usergoal'
goal.id = 'UserGoal'+j
var del = document.createElement('button')
del.className = 'deleteButton'
del.innerHTML = 'Delete Goal'
del.id = j
var com = document.createElement('button')
com.className = 'completedButton'
com.innerHTML = 'Not Completed'
com.id = j
j++
com.onclick = function(e){
if (com.innerHTML == 'Not Completed' ){
var dec = window.prompt('Are you sure? this action can not be undo type y/n')
if (dec == 'y'){
com.innerHTML = 'Completed'
var ele = e.target.id
var fin = 'UserGoal'+ele
document.getElementById(fin).style.textDecoration='line-through'
}
}
}
divTag.appendChild(goal)
divTag.appendChild(del)
divTag.appendChild(com)
parentElement.appendChild(divTag)
del.onclick = function(e){
var id_toDelete = e.target.id
var id_section = 'goal- ' + id_toDelete
alert(id_section)
parentElement.removeChild(divTag)
}
}
body{
background-color: #003f5c;
}
h1{
display: flex;
justify-content: center;
font-size: 60px;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}
.btnConatiner{
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 40px;
}
#newGoalBtn{
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 50px;
font-size: 30px;
border-radius: 15px;
border: solid 5px black;
cursor: pointer;
}
.goalsSection{
border: solid 6px white;
width: 200px;
height: 100px;
border-radius: 20px;
background-color: white;
margin: 10px;
float: left;
}
.usergoal{
text-align: center;
font-size:20px;
}
.deleteButton{
cursor: pointer;
}
.completedButton{
cursor: pointer;
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Goal Tracker</title>
</head>
<body>
<h1>Goal Tracker</h1>
<div class="btnConatiner">
<button id="newGoalBtn" onclick="addGoal()">New Goal</button>
</div>
<section class="add-goals">
<div id="new-goals">
</div>
</section>
<script src="app.js"></script>
</body>
</html>
Inside the function addGoal, you can get all the goals that are already on the localstorage, and then push a new goal into the array and store.
// const goals = localStorage.getItem("goals") || []; // you can declare here too.
function addGoal() {
const goals = localStorage.getItem("goals") || [];
const userGoal = window.prompt("Enter goal:")
goals.push(userGoal)
localStorage.setItem('goals', JSON.stringify(goals)) // you need to transform into string
...
And then you can create a function to render the goals that are on the localstorage, like:
function renderGoals() {
const goals = JSON.parse(localStorage.getItem("goals")); // parsing back
// Then you can iterate on these goals (forEach for example) to render.
...
}
You can use localStorage, but not to store all the HTML you're creating, rather to store the essential data. And from that data, you can easily rebuild your html.
First keep track of your data, and set up your addGoal function to accept an argument for the rebuilding (after page refresh)
let userGoals = [] // leave this empty for the moment
function addGoal(userGoal){
if (!userGoal) { // this is a new one, so we'll store it in the array and localStorage
userGoal = window.prompt('Enter goal: ')
userGoals.push(userGoal);
localStorage.setItem('userGoals', JSON.stringify(userGoals)); // localStorage stores everything as strings so we stringify it
}
//... the rest of this function
Then at the bottom of your script, create a window.onload function that runs once, when the page first loads. If there is data in localStorage, this will create your User Goals list
window.onload = function() { // this runs after the page has loaded
if (localStorage.getItem('userGoals') ) { // if we have localStorage values waiting for us, parse them and iterate through them
JSON.parse(localStorage.getItem('userGoals')).forEach(goal => {
userGoals.push(goal)
addGoal(goal)
});
}
}
...

How can i execute a javascript function in HTML?

i have a javascript code that setup a websocket connection and have several functions.
The websocket works fine.
but i want to run a javascript function from the script inside the html code.this does not work. if i run the function from a onclick event, then it works fine (see the button).
i have tried the body onload but it does not work.
My goal is: execute the function OnloadFunction if the webpage is loaded. Then it should send a string with websocket.
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
<script>
var connection;
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
function OnloadFunction() {
connection.send('* Test22');
alert("Hello! ");
}
</script>
</head>
<body onload="javascript:OnloadFunction();">
<h1>Testpage</h1>
<p>Suche....</p>
<p><button class="button" onclick="OnloadFunction()">read</button></p>
</body>
</html>
This is a simple test from me but does not work also
<body>
<h1>Test</h1>
<p>Suche...</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
<script>
var connection = new WebSocket('ws://' + window.location.hostname + ':81/');
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function (e) { console.log('Server: ', e.data);};
connection.send('* Test22');
</script>
</body>
What is wrong? How can i execute the function OnloadFunction() in the html code if the webside is loaded?
EDIT1:
Thank you for all the suggestions. i have tried much different ways but nothing works.
Now I am close to a solution but I do not understand the new error.
The function start() is executet because of window.onload=start;
But the code after connection.onmessage = function(evt) { console.log(evt);};
is only executet if the alert("TEST___"); is in the code. if i delete this line then the code after that is not executet. Why is the code not executet without alert("TEST___"); ?? With the button onclick all works well without the alert.
Here my code websock2.js (the alters are only for testing):
var connection;
function OnloadFunction() {
connection.send('* Test22'+' x');
alert("LOADED! ");
}
function start() {
alert("Start! ");
connection = new WebSocket('ws://' + window.location.hostname + ':81/');
<!-- connection = new WebSocket('ws://192.168.1.5:81/',['arduino']); -->
connection.onopen = function () { connection.send('Connect ' + new Date()); };
connection.onerror = function (error) { console.log('WebSocket Error ', error);};
connection.onmessage = function(evt) { console.log(evt);};
alert("TEST___");
connection.send('* Test22'+' x');
console.log('effekt: ');
alert("LOADED! ");
}
window.onload=start;
Here my html code:
<!DOCTYPE html><html>
<head>
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"icon\" href=\"data:,\">
<title>Testpage</title>
<meta charset="UTF-8">
<script src="websock2.js" async></script>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center; background-color:#5593F1}
.button { background-color: #195B6A; border: none; color: white; padding: 10px 40px;
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
.button2 {background-color: #77878A;}
</style>
</head>
<body>
<h1>Testpage</h1>
<p>read....</p>
<p><button class="button" onclick="OnloadFunction()">Lesen</button></p>
</html>

I want to save textbox to .txt file in HTML using JavaScript but I have an error

I have a fake web site for a school project and I want to get the HTML code to send the information from textbox to .txt file with Javascript, but it doesn't work and I don't know why. Can you tell me where the error is, please?
<section>
<form method:"POST">
<label>Escrigui el seu usuari:</label>
<input type="text" name="usuari" id="usuari" size="20"/>
<label>Escrigui la seva contrasenya:</label>
<input type="text" name="contrasenya" id="contrasenya" size="20"/>
<input type="button" value="submit" id="button" href="" onclick="WriteToFile()"/>
</form>
<script type="text/javascript">
function WriteToFile(passForm){
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("filename.txt", True);
var usuari = document.getElementById("usuari").value;
var contrasenya = document.getElementById("contrasenya").value;
s.writeline("usuari :" + usuari);
s.writeline("contrasenya :" + contrasenya);
s.writeline("-----------------------------");
s.Close();
}
</script>
I've programmed a "Notebook" that exports the input to a txt file which is ready to be downloaded after:
<html><head>
<style>
body {
margin: 0%;
}
#font-face {
font-family: "CG";
src: url(./resources/CENTURYGOTHIC.ttf) format("truetype");
}
textarea {
margin-left: 0%;
margin-top: 0%;
height: 80%;
width: 100%;
resize: none;
visibility: visible;
background-color: white;
border-color: black;
}
button {
background-color: white;
font-family: CG;
border-color: black;
border-width: 1px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 20px;
padding-left: 20px;
margin-top: 10px;
text-transform: capitalize;
}
</style></head>
<body>
<textarea id="textbox" placeholder="You can write anything here... just start tyipng what you would like to remember: Notes, Homework, Tests, just anything."></textarea>
<button id="create">SAVE TO FILE</button>
<a download="notes.txt" id="downloadlink" style="display: none"><button onclick="functionreset()">DOWNLOAD</button></a>
<br>
<script>
(function() {
var textFile = null,
makeTextFile = function(text) {
var data = new Blob([text], {
type: 'text/plain'
});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function() {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
document.getElementById('create').style.display = 'none';
}, false);
})();
function functionreset() {
var link = document.getElementById('downloadlink');
link.style.display = 'none';
document.getElementById('create').style.display = 'block';
}
</script>
<script>
document.getElementById("textbox").onchange = function() {functionreset()}
</script>
<!-- <iframe height=100% width=100%; src=./test.html></iframe>-->
</body></html>
maybe you can use fragments of this...
Notify me if it worked😉

Chat with only javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to make a chat in a long time, but I had no succes in making it.
I tried alot of ways, but making it insert the msg to my database and then with javascript refresh the chat every second, and get the msg from database, but that dosent work that well.
I was wondering is theire a way to make a chat with only javascript?
So it appends to a div all the users can see.
I saw some sites do this but I haven't been able to do it myself.
Yes - You can make a chat client that takes advantage of Websockets.
The only thing required is that you run a server in order to forward requests to other clients as they arrive.
The server can be written in a variety of different languages -- some of the most popular are C/C++ (Qt), node.js, Python, and go.
There are more languages which can provide this as ability as well ---
This came from http://www.tutorials.kode-blog.com/websocket-chat-client
var output;
var websocket;
function WebSocketSupport() {
if (browserSupportsWebSockets() === false) {
document.getElementById("ws_support").innerHTML = "<h2>Sorry! Your web browser does not supports web sockets</h2>";
var element = document.getElementById("wrapper");
element.parentNode.removeChild(element);
return;
}
output = document.getElementById("chatbox");
websocket = new WebSocket('ws:localhost:999');
websocket.onopen = function(e) {
writeToScreen("You have have successfully connected to the server");
};
websocket.onmessage = function(e) {
onMessage(e)
};
websocket.onerror = function(e) {
onError(e)
};
}
function onMessage(e) {
writeToScreen('<span style="color: blue;"> ' + e.data + '</span>');
}
function onError(e) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + e.data);
}
function doSend(message) {
var validationMsg = userInputSupplied();
if (validationMsg !== '') {
alert(validationMsg);
return;
}
var chatname = document.getElementById('chatname').value;
document.getElementById('msg').value = "";
document.getElementById('msg').focus();
var msg = '#<b>' + chatname + '</b>: ' + message;
websocket.send(msg);
writeToScreen(msg);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
function userInputSupplied() {
var chatname = document.getElementById('chatname').value;
var msg = document.getElementById('msg').value;
if (chatname === '') {
return 'Please enter your username';
} else if (msg === '') {
return 'Please the message to send';
} else {
return '';
}
}
function browserSupportsWebSockets() {
if ("WebSocket" in window) {
return true;
} else {
return false;
}
}
body {
font: 12px arial;
color: #222;
text-align: center;
padding: 35px;
}
#controls,
p,
span {
margin: 0;
padding: 0;
}
input {
font: 12px arial;
}
a {
color: #0000FF;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
#wrapper,
#loginform {
margin: 0 auto;
padding-bottom: 25px;
background: #66CCFF;
width: 504px;
border: 1px solid #ACD8F0;
}
#chatbox {
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 270px;
width: 430px;
border: 1px solid #ACD8F0;
overflow: auto;
}
#chatname {
width: 395px;
border: 1px solid #ACD8F0;
margin-left: 25px;
float: left;
}
#msg {
width: 395px;
border: 1px solid #ACD8F0;
}
#submit {
width: 60px;
}
<!DOCTYPE html>
<html>
<head>
<title>WebSocket PHP Open Group Chat App</title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script src="websocket_client.js"></script>
</head>
<body onload="javascript:WebSocketSupport()">
<div id="ws_support"></div>
<div id="wrapper">
<div id="menu">
<h3 class="welcome">Welcome to WebSocket PHP Open Group Chat App v1</h3>
</div>
<div id="chatbox"></div>
<div id="controls">
<label for="name"><b>Name</b>
</label>
<input name="chatname" type="text" id="chatname" size="67" placeholder="Type your name here" />
<input name="msg" type="text" id="msg" size="63" placeholder="Type your message here" />
<input name="sendmsg" type="submit" id="sendmsg" value="Send" onclick="doSend(document.getElementById('msg').value)" />
</div>
</div>
</body>
</html>

Categories

Resources