get cookie with specific name [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
i want to check existence of a cookie in html,
here is my code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
$cookie_name = 'testhastin';
if(!isset($_COOKIE[$cookie_name])) {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>
but when i run this page, noting will happen for "a1 test". (meaning it does not change to "not set")
i want to check if a cookie exists on the page and if so show specific content.
i also tried this code and result was the same:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="a1">
<p id = "ttttt">a1 test</p>
</div>
<script>
function checkCookie() {
var username = getCookie("testhastin");
if (username != "") {
document.getElementById("ttttt").innerHTML = "set";
} else {
document.getElementById("ttttt").innerHTML = "not set";
}
}
window.checkCookie();
</script>
</body>
</html>

$_COOKIE is a PHP variable. isset() is a PHP functoin. You cannot use that in JavaScript.
As for fetching cookies use document.cookiename
// Setting a cookie
document.testhastin= "Akshay";
// Reading a cookie
var val = document.testhastin;
W3Schools Link : https://www.w3schools.com/js/js_cookies.asp

Related

Cannot read properties of null (reading 'addEventListener') in a Javascript file (not script tag) [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed last year.
I am a JavaScript beginner and when I was making a HTML, CSS, JS project with VSCode, I encountered the following error:
Uncaught TypeError: Cannot read properties of null (reading at 'addEventListener')
Also, My project was: Make a login + register system with just JavaScript dictionaries, and a logged_in variable (that will redirect people to the registration page if it's false)
HTML Registration file:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>BeedHub Register</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='style.css'>
<script src='index.js'></script>
</head>
<body>
<h1 class="hello_world">Welcome!</h1>
<p class="aaa">We're so excited to see you!</p>
<div class="usernamediv">
<input id="main_usr" placeholder="Write username here" type="text">
</div>
<div class="passworddiv">
<input id="main_pw" placeholder="Write password here" type="password">
</div>
<div class="btn">
<button id="main_register">Register!</button>
</div>
<div class="login_instead">
Login Instead
</div>
</body>
</html>
JavaScript file:
// Variables
var db = {
};
var logged_in = false;
// Register Elements
var rg_usr = document.getElementById("main_usr");
var rg_pw = document.getElementById("main_pw");
var rg_submit = document.getElementById("main_register");
// Event Listeners
rg_submit.addEventListener('click',function() {
if (db[rg_usr.innerHTML]) {
var error_usr_taken = document.createElement("p");
error_usr_taken.innerHTML = "Error: Username Already Taken!";
} else if (rg_usr.innerHTML == "" || null) {
var error_usr_none = document.createElement("p");
error_usr_none.innerHTML = "Error: Username is null!";
} else if (rg_pw.innerHTML == "" || null) {
var error_pw_none = document.createElement("p");
error_pw_none.innerHTML = "Error: Password is null!";
} else {
db[rg_usr.innerHTML] = rg_pw.innerHTML;
logged_in = true;
window.location.pathname = "/successpage";
};
});
If you want me to provide more information, comment with a ping.
P.S. I have also used the script tag on my /login/index.html file, but the web says that multiple HTML files using the same JavaScript file have no problem.
Thanks in advance,
Beedful
Your script is being executed before the markup is on the page and that's why you're getting an error.
So, you can either move the script tag at the very end of the body like this:
<body>
<!-- All contents here -->
<script src='index.js'></script>
</body>
Or you can add defer to your script tag and let it continue to be in the head, like this:
<script src='index.js' defer></script>

Trying to make a notepad like script in HTML/JS

Edit: Just confirming: I want what the user typed to be saved so that when he reloads/leaves the webpage and comes back what he wrote earlier is still there.
I tried using cookies but it only put one line of Default(variable) when I reloaded the page. Im trying to get it to work with localStorage now but it sets the textarea to "[object HTMLTextAreaElement]" or blank when I reload. I read that this error can be caused by forgetting to add the .value after getElementById() but I did not make this mistake. I am hosting and testing the webpage on Github(pages). What am I doing wrong? here is the code(ignore the comments also it might not work in jsfiddle bc it localstorage didn't work there for me):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>le epic web page</title>
</head>
<body><!--
= "\n"-->
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
<script>
var Default="P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if(localStorage.getItem("P") == ""){
document.getElementById("txt").value=Default;
localStorage.setItem("P")=Default;
}else{
document.getElementById("txt").value=localStorage.getItem("P");
}
//update cookie (called when typed)
function save(){
var txt=document.getElementById("txt").value;
//txt=txt.replace(/\r\n|\r|\n/g,"</br>");
localStorage.setItem("P",txt);//set cookie to innerHTML of textArea, expires in 1 day
}
//when page closed/reloaded
window.onbeforeunload = function(){
localStorage.setItem("P",txt);//update cookie when page is closed https://stackoverflow.com/a/13443562
}
</script>
</body>
</html>
When you are exiting the page, you are referencing the text element and storing that in localstorage. Since localStorage is a string it converts the html element reference into the text you see.
window.onbeforeunload = function(){
localStorage.setItem("P",txt);
}
You are doing it correctly with save, so just call save with the beforeunload event
window.addEventListener('beforeunload', save);
Another bug in the code is the line
if(localStorage.getItem("P") == ""){
when localStorage is not set, it returns null. So the check would need to be a truthy check ( or you can check for nullv)
if(!localStorage.getItem("P")){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>le epic web page</title>
</head>
<body>
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
</body>
<script>
const Default =
"P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if (
localStorage.getItem("P") === "" ||
localStorage.getItem("P") === null ||
localStorage.getItem("P") === undefined
) {
localStorage.setItem("P", Default);
} else {
let currentValue = document.getElementById("txt");
currentValue.value = localStorage.getItem("P");
}
function save() {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
}
window.onbeforeunload = function () {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
};
</script>
</html>

Check weather internet is available or not [duplicate]

This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 5 years ago.
I need some help with my html code. I need to integrate javascript in it which upon loading checks whether internet is available or not. If active it should perform specific task, else it should show "no internet".
`<html>
<head>
</head>
<body onload="myClickHandler();
startTime()">
<script language="JavaScript">
var t;
document.onclick = myClickHandler;
function myClickHandler() {
clearTimeout(t);
t = setTimeout("location.href='index.html'", 60000);
//for refreshing the page in every 60 sec.
}
</script>
<h1> test </h1>
<script type="text/javascript">
var url = "https://www.google.co.in";
var img = new Image();
img.src = url;
img.onerror = function()
{
// If the server is down, do that.
alert ("no connection");
}
img.onload = function()
{
// If the server is up, do this.
//some task to perform.
return true;
}
</script>
</body>
</html>`
This is what i code, but page is keep on loading after the performance also we need to manually stop the loading.
Use the below code. Thanks to this post .
To know more about navigator.online plz check the below link
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
<!doctype html>
<html>
<head>
<script>
function CheckOnlineStatus(msg) {
var status = document.getElementById("status");
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
var state = document.getElementById("state");
state.innerHTML = condition;
}
function Pageloaded() {
CheckOnlineStatus("load");
document.body.addEventListener("offline", function () {
CheckOnlineStatus("offline")
}, false);
document.body.addEventListener("online", function () {
CheckOnlineStatus("online")
}, false);
}
</script>
<style>
...</style>
</head>
<body onload="Pageloaded()">
<div id="status">
<p id="state">
</p>
</div>
</body>
</html>

I want to check if parameter exist as an id in the body. how can I do that without hardcoding and using jquery? Javascript [duplicate]

This question already has answers here:
How to append text to a div element?
(12 answers)
Closed 5 years ago.
<a id="Param">This is an html element</a>
<script>
function Append(param1,text)
{
if(document.getElementById(param1))
{
return document.getElementById(param1)+text;
}
else
{
console.error("the element was not found");
}
}
var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?
A string-query might be your best bet by making the PARAM dynamic and you can change it based on what the url passes to the script. index.php?param1=myvalue
Here is a reference article I used last time I had to do it myself: https://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/
Respectfully,
SFR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>
<a id="Param">This is an html element</a>
<script>
function appendToElement(p1,p2)
{
var el=document.getElementById(p1);
if(el)
{
el.innerHTML+=p2;
return true;
}
else
{
console.error("Element with ID: "+p1+" not found");
return false;
}
}
var app1=appendToElement("Anything",". yes");
var app2=appendToElement("Param",". hi")
</script>
</body>
</html>
This is the code that I got from my professor.

Why the value of document.getElementById("greeting") is null? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
<!-- This is the HTML element -->
<h1 id="greeting"></h1>
JS
var currentUser = localStorage.getItem("currentUser");
document.getElementById("greeting").innerHTML = "Hi " + currentUser;
Here is what happens when inspect the page, it says:
Uncaught TypeError: Cannot set property 'innerHTML' of null(…)
This would be the entire code file.
//mypublicwebsites.tk/artem/databases/a/load_home.js
//This isn't the complete code because I cannot use 'localStorage' in a code snippet
//excluding unneeded code
var isSignedIn = true;
//The current user, lets just say that is me
var currentUser = "Sean";
if(isSignedIn) {
load();
} else {
window.location.replace("index.html");
}
function logOut () {
localStorage.setItem("isSignedIn","false");
localStorage.setItem("currentUser", "none");
window.location.replace("index.html");
}
function load() {
document.querySelector(".greeting").innerHTML = "Hi " + currentUser + "!";
}
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="mypublicwebsite.tk/artem/databases/a/load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
It does seem to work in the snippet but not in the browser.
Fine, I'll post the answer I found. You need to wait for the webpage to load and then execute the script, so I put the script right before the closing body tag.
After checking your source over at Github i notice that there is no element of id greeting at https://github.com/codecademy123/codecademy123.github.io/blob/master/artem/databases/a/home.html :
<!DOCTYPE html>
<html>
<head>
<title>Artem Inc. | Database A -> Home</title>
<script src="load_home.js"></script>
</head>
<body>
<div id="menu">
<button onclick="logOut()">Log Out</button>
</div>
<h1 class="greeting"></h1>
</body>
</html>
No id but there is a class with the name greeting.
Here's an updated and simplified fiddle:
https://jsfiddle.net/tommiehansen/ndd0c7rh/2/
Basically we just use document.querySelector('.greeting') instead of document.getElementById('greeting') since the id greeting will always return undefined if it does not exist.
If you want to still use an id simply change the source code for home.html from <h1 class="greeting"></h1> to <h1 id="greeting"></h1>. The important part here is to query the DOM after what you've set the class or id to be. Because if you do not match these it will always return as undefined since your javascript will not be able to find the selector.

Categories