- Passing a variable from node.js to html
- How to Use Javascript Variable in HTML
- Linking Javascript Variable to HTML Element
- Using Javascript Array Variable in HTML
- About
- Recent Posts
- Use JavaScript Variable in HTML
- JavaScript User Defined Variable Usage in HTML
- JavaScript Variable Loaded From Prompt
- Create a Tag Element From Script and Variable Access to HTML
- Related Article — JavaScript Variable
Passing a variable from node.js to html
@AstemirAlmov He is most surely not using HTML, he must be using EJS. Have a look here: ejs.co . This is what we use with nodejs.
I found the possible way to write.
app.engine('html', require('ejs').renderFile); app.get('/main', function(req, res) < var name = 'hello'; res.render(__dirname + "/views/layouts/main.html", ); >);
What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:
- npm install —save pug — to add it to the project and package.json file
- app.set(‘view engine’, ‘pug’); — register it as a view engine in express
- create a ./views folder and add a simple .pug file like so:
html head title= title body h1= message
note that the spacing is very important!
This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html
For more info on pug you can also check: https://github.com/pugjs/pug
Sorry, I know it completely unrelated to this, but I’m having a problem when passing a variable to my view, and it is really weird. The templates renders perfectly fine, but then in the console (and randomly, there isnt a clear pattern), sometimes throws the error of can not read property X of undefined . but, at the same time the UI renders exactly as it should. Do you have any idea about this?
Do you have any javascript on the page? If you do, check who/what is trying to access a field named «X». It should be something along the lines of something.X
I figured out. Never saw this before, but it only happened when dev tools was opened, so then I realised that the server was throwing a 500 error because dev tools was trying to access jquery.min.map (which I didnt have in the vendor folder), so the 500 error was interrupting express and therefore the variables were not passing.
To pass variables from node.js to html by using the res.render() method.
var bodyParser = require('body-parser'); var express = require('express'); var app = express(); app.use(express.static(__dirname + '/')); app.use(bodyParser.urlencoded()); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.set('views', __dirname); app.get('/', function(req, res)< res.render('index.html',); >);
With Node and HTML alone you won’t be able to achieve what you intend to; it’s not like using PHP, where you could do something like , without any other stuff installed.
To do what you want using Node, you can either use something that’s called a ‘templating’ engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.
Both require some extra work; it’s not as plug’n’play as PHP when it comes to doing stuff like you want.
@Bahgat Mashaly then you do not mind posting an example and showing the rest of the world how that works ? Because the thing you just copy pasted is not native nodeJS. seems like a template engine module that you installed on top of nodeJS.
use res.json, ajax, and promises, with a nice twist of localStorage to use it anywhere, added with tokens for that rare arcade love. PS, you could use cookies, but cookies can bite on https.
function (idToken) < $.ajax(< url: '/main', headers: < Authorization: 'Bearer ' + idToken >, processData: false, >).done(function (data) < localStorage.setItem('name', data.name); //or whatever you want done. >).fail(function (jqXHR, textStatus) < var msg = 'Unable to fetch protected resource'; msg += '
' + jqXHR.status + ' ' + jqXHR.responseText; if (jqXHR.status === 401) < msg += '
Your token may be expired' > displayError(msg); >);
app.get('/main', passport.authenticate('oauth2-jwt-bearer', < session: false >), function (req, res) < getUserInfo(req) //get your information to use it. .then(function (userinfo) < //return your promise res.json(< "name": userinfo.Name>); //you can declare/return more vars in this res.json. //res.cookie('name', name); //https trouble >) .error(function (e) ) .catch(function (e) ); >);
I have achieved this by a http API node request which returns required object from node object for HTML page at client ,
for eg: API: localhost:3000/username
returns logged in user from cache by node App object .
app.get('/username', function(req, res) < res.json(< udata: req.session.user >); >);
If using Express it’s not necessary to use a View Engine at all, use something like this:
This works if you previously set your application to use HTML instead of any View Engine
this answer is wrong. The << >> indicates that some form of templating engine is used, most likely handlebars.<>
Other than those on the top, you can use JavaScript to fetch the details from the server. html file
app.get('/test',(req,res)=>< //res.sendFile(__dirname +"/views/test.html",); res.json(); >) app.get('/render',(req,res)=>< res.sendFile(__dirname +"/views/test.html"); >)
The best answer i found on the stack-overflow on the said subject, it’s not my answer. Found it somewhere for nearly same question. source source of answer
I resolved this using cookies, it may help you if you don’t want to pass any sensitive values to the client, and only using VanillaJS and Node.js with Express. I set the values as cookies using the cookie method of res object in my request function:
app.post('/app/login',(req, res) < // (POST, '/app/login') const user = req.body.user; sessions.push(< sessionId, user>); res.cookie('user', user); res.sendFile('inicio.html'); >);
It’s important to see that I sent an HTML file to the client, later, in the JavaScript file linked to this, I created this function:
document.addEventListener("DOMContentLoaded", ()=> < const username = document.cookie.slice(5); document.querySelector("#user_h3").innerHTML += username; >);
The selector «#user_h3», refers an h3 tag that can chage its content by the innerHTML property using QuerySelector. The HTML looks like this:
How to Use Javascript Variable in HTML
You can only use Javascript variable in HTML by linking the Javascript variable to a HTML element using an id or class attribute.
Linking Javascript Variable to HTML Element
Assign an id to the element.
id="content-holder">Content is loading .
If you check this now all you will see is:
You can now add Javascript to your page using script tags.
// Write your Javascript code inside here
Now, you can start working on the Javascript. Create your Javascript Variable.
var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript.";
You grab the element in Javascript using the assigned id value.
var contentHolder = document.getElementById('content-holder');
To display the variable in HTML, assign the variable to the element in Javascript using the innerHTML property.
contentHolder.innerHTML = newContent;
Complete Code
id="content-holder">Content is loading . // Write your Javascript code inside here var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript."; var contentHolder = document.getElementById('content-holder'); contentHolder.innerHTML = newContent;
You can use the above method for string and number variables.
Using Javascript Array Variable in HTML
To view array and object variables in HTML, you have to loop through the items in Javascript before passing them to HTML.
You can also interact with the code for this project.
Hi there! I am Avic Ndugu.
I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.
Front End Developer Newsletter
Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.
Start understanding the whole web development field now
Stop all the confusion and start understanding how all the pieces of web development fit together.
Never any spam, easily unsubscribe any time.
About
If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.
Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.
You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.
Recent Posts
Copyright © 2018 — 2023 DevPractical. All rights reserved.
Use JavaScript Variable in HTML
- JavaScript User Defined Variable Usage in HTML
- JavaScript Variable Loaded From Prompt
- Create a Tag Element From Script and Variable Access to HTML
JavaScript variables are often user-defined while coding, or you can use prompt to fetch data and store it in a variable for further use.
Here, we will show how to act upon a user-defined variable and use it in HTML, and the later demonstration will explain how the prompt can help us in this regard.
JavaScript User Defined Variable Usage in HTML
We are using jsbin for the code examples, and here you will see the p element is identified by the id output . Initially, the variable myPet is set to be Tobey , and the later simple line was executed in the webpage. getElementById finds the preferred id , and later the variables are passed in the inner.HTML format so the JavaScript variables can be used in the HTML .
html lang="en"> head> meta charset="UTF-8"> title>Testtitle> style> p background: pink; > style> head> body> p id="output">p> body> html>
var myPet = "Tobey"; var nameLength = myPet.length; document.getElementById('output').innerHTML = myPet + " is a " + nameLength + " letter name!";
JavaScript Variable Loaded From Prompt
In this segment, we will see how we easily input value in the prompt window, and that directly is displayed in our loaded webpage.
html lang="en"> head> meta charset="UTF-8"> title>Testtitle> style> p background: pink; > style> head> body> p id="output">p> body> html>
var myPet = prompt(); var nameLength = myPet.length; document.getElementById('output').innerHTML = myPet + " is a " + nameLength + " letter name!";
Create a Tag Element From Script and Variable Access to HTML
Here, we will create a p tag in the script, which will be accessible in the HTML body . The p.innerHTML is the key to passing the variable data towards the body tag.
html lang="en"> head> meta charset="UTF-8"> title>Testtitle> style> p background: gray; color: white; text-align: center; > style> head> body> body> html>
var myPet = prompt("Enter Name") ; var nameLength = myPet.length; p = document.createElement("p"); p.innerHTML = myPet + " is a " + nameLength + " letter name!"; document.body.appendChild(p);
Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.
Related Article — JavaScript Variable
Copyright © 2023. All right reserved