Pass variable from ajax to jade/pug - node.js

Am obtaining the values from nodejs via ajax/fetch and need to pass the same to Pug.
Any help here would be much appreciated
sample.pug
button#searchVal Search
script(type='text/javascript', src='/lib/onClick.js')
br
br
table#table(div='')
each row in slaJobs
tr
th#cbs-tab-header(div='') !{row.jobname}
th#cbs-tab-header(div='') !{row.job_type}
th#cbs-tab-header(div='') !{row.autosys_instance}
dummy.js
.then(function(data) {
console.log(data.jobsHeader)
console.log(data.slaJobs)
})
Need to set value of data.slaJobs from js to slaJobs of Pug

if you can afford to refresh the pug page for the result:
make a request with ajax to some route in node.js.
in the route handler - where you render the pug view - you can pass arguments to your view template.
so when the pug page will be rendered - It will already contain your data.
if you can't afford to refresh:
1. script tag in your template. handle the response and inject the data to the HTML page like any other AJAX

if you are getting data via ajax you should iterate the payload data in a forEach loop and generate HTML into current document. Actually pug is rendered on the server and then the output as HTML will be given to the user.
You can't show your data in your pug view engine while it is already rendered and shown to the user.
a sample:
fetch('localhost:3000/products')
.then(data => data.json())
.then(data => {
var div= document.getElementById('div');
data.forEach(item=>{
var p = document.createElement('p');
p.textContent = item[0] + ' ' + item[1];
div.appendChild(p);
}
})

Related

How to pass values and link next page throw href tag in pug

In pug file i have values in "n" i have to pass the values throw the href tag to next page. How to change in href tag. it should be a link not a button.
a(Class=`change_pasword` onclick=`next('${n}')`) Change Password
script.
function next(parmas) {
window.location.href = `/update_password?user_details=${parmas}`
}
How to change the code to href?
You can use just a regular link if you convert the js object to a query string within Pug first.
- const serialize(obj) { ... } // use the formula from the linked answer
a.change_password(href=`/update_password?user_details=${serialize(n)}`) Change Password

POST FORM in node and receive data response back to same webpage

I have a webpage that takes form details, POSTS the data and should then show the results. I'm using express for my routing.
This all works fine by resending the data with the HTML template after the POST but I think there must be a better way by hiding the "results" HTML section then just showing it once the data is known from the form. I've shown a cutdown version of my pages below.
On first load, the page says "your result is undefined", which I would expect but is ugly.
I could remove the "result" section and create a 2nd HTML page to resend from the POST route with it in which would work but I think there must be a better way.
I want to hide the result section on 1st page load then make it appear on the button submit with the result data. I can get the section hide/unhide but I can't get the data results back to display them. On button submit the form results just appear in the weburl www.mywebsite.com/?data almost like a GET request
I have tried using FormData and npm 'form-data' in a POST but can't get it working following these examples https://javascript.info/formdata and https://www.npmjs.com/package/form-data.
My structure in Node is
Router.js file
return res.send(htmlFormTemplate({}));
});
router.post('/css',
[],
async (req, res) => {
let {data} = req.body;
///
result= do some calculation on {data}
///
return res.send(htmlFormTemplate({result}));
});
The htmlFormTemplate is a js file
module.exports = ({result}) => {
return `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="box" method ="POST">
<inputname="data" />
<button>Submit</button>
</form>
<script>
///tried form processing here
</script>
<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>
</body>
</html>
`;
};
I'm self-taught and new so hope this makes sense and thanks for any help/ideas
You can check if the result variable is null before it gets to the section div:
${ result === null ? '' :
`<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>`}
Like this, it wont show the result div if result if null.
There is a very simple to solve this problem,
just use some templating engine for ex EJS, its very easy to use and will help you better,
and your result is undefined because your using a promise and it might have happened that the response might have not come and you loaded the page. Just use await
return await res.send(htmlFormTemplate({result}));

rendering returned html code to be shown as a view

so i'm saving the current Date in a cookie and I try to show the value of this cookie in a html web page using a template engine. The problem is when i send my new template which contains the Date, i get a HTML text instead of a view.
router.get('/', (req, res) => {
let template = fs.readFileSync(indexFile, 'utf8');
var dataToShow = {"cookie_data": 'Letzte Besuch: ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()};
template = mustache.render(template, dataToShow);
res.send(template);
})
And in my HTML page i have the following :
<p>{{cookie_data}}</p>
I expect to have a view instead of html-code
Please try using
<p>{{{cookie_data}}}</p>
Please refer this doc: http://handlebarsjs.com/#html-escaping
Please use
res.render('page', 'params')

Cheerio how to ignore elements of a certain tag

I am scraping the body of the webpage:
axios.get(url)
.then(function(response){
var $ = cheerio.load(response.data);
var body = $('body').text();
});
The problem is, I want to exclude contents from the <footer> tag. How do I do that?
cheerio creates a pseudo-DOM when it parses the HTML. You can manipulate that DOM similar to how you would manipulate the DOM in a browser. In your specific case, you could remove items from the DOM using any number of methods such as
.remove()
.replaceWith()
.empty()
.html()
So, the basic idea is that you would use a selector to find the footer element and then remove it as in:
$('footer').remove();
Then, fetch the text after you've removed those elements:
var body = $('body').text();

Gathering document fragments at rendring time using `pug`

I use pug to generate HTML email messages from a template:
doctype html
html
head
title Hello #{name}
body
...
The title is the subject of the email.
Currently, I extract the title text content by parsing the HTML document rendered by pug. But it doesn't seem to be a very efficient way of doing.
Is there some feature or hook available in pug to collect part of the document while rendering it? I considered pug filters, but as far as I understand, those are not suitable since they are triggered at compile time. Not while rendering the document.
I came to a solution using a mixin:
mixin collect(name)
-
// This is just an ugly hack to
// capture the inner block rendered
// text
const savedHtml = pug_html;
pug_html = "";
if (block) block();
const innerHtml = pug_html;
self[name]=innerHtml;
pug_html = savedHtml+innerHtml;
html
head
title
+collect('title')
| Hello #{self.name}
var pug = require("pug");
const compiledFunction = pug.compileFile('template.pug', {debug:true,self:true});
console.log(compiledFunction(out={
name: 'Timothy',
}));
console.log(JSON.stringify(out));
Displaying:
<html><head><title>Hello Timothy</title></head></html>
{"name":"Timothy","title":"Hello Timothy"}
The code of the collect() mixin is not particularly pretty because as far as I know it there is no elegant way to capture the block() output. So I had to tackle into the internal undocumented pug_html variable.
Or is there a cleaner way to achieve that?

Resources