load a returned HTML file - javascript

I have a HTML button, upon clicking, it will send a get request to get a HTML file, and I would like to load the got HTML file to replace the current HTML file I have.
The frontend codes look like this:
document.getElementById("single_user_button").onclick = function() {
$.get('/profile', {token: idToken}, (res) => {
console.log(res);
})
}
And I am using an Express router to handle this:
router.get("/profile", (req, res) => {
res.sendFile(path.join(__dirname, "../public/html/main/ll_profile.html"));
});
I can see the ll_profile.html in the res variable. But I have no idea how to load it up to replace the current HTML page. I tried the JQuery .load(), but that is for loading into an ID. How should I do this?

Related

How do I send variables from multiple js files to one ejs file?

I have one js file that sends a couple variable to ejs and that works, but when I try to run a second node js process running another js file, it seems like it won't look in the process that I run second.
What do I need to do to get the ejs file to recognize and receive variable from the second js file?
On the webpage, I get <var> is not definedand it traces back to a render from the first js file even though I'm rendering it from the second js file.
I'm sending it using the following code:
app.get('/', (req, res) => {
res.render('main', {
variable: value
}
});
edit:
Trying my best to add an example...
first.js:
var variable1 = value1;
app.get('/', (req, res) => {
res.render('main', {
variable1: value1
}
});
second.js:
var variable2 = value2;
app.get('/', (req, res) => {
res.render('main', {
variable2: value2
}
});
When I load main.ejs, it says it can't find variable2 in first.js.. why is it looking in first.js for the variable, even though I'm passing it from second.js?
I have first.js that calculates some variables and passes it to main.ejs. I also have second.js that runs separately from first.js that does the same thing.
It doesn't run separately… or at all.
HTTP is based on the simple system of:
A client (like a web browser) asks for something
The server (like your Express.js based program) responds with something
And those somethings are single somethings.
So the browser sends a request for /, and then Express looks through the registered routes until it finds a match.
app.get('/', (req, res) => {
res.render('main', {
variable1: value1
}
});
It runs that function and generates a response.
It never gets to the other function registered for the same route: It has already found a route that allowed it to provide a response. If it kept going and sent another response, then it would be a completely different execution of the EJS script, and a completely different response that the browser wouldn't be expecting.
Write one route for handling /.
Call render once and pass it an object with all the data you want
Split the code up into functions if you want to make it easier to manage. One of the functions can be the route handler itself, and it can call the others and get the data they return. If things get really complex, you can move the functions into separate modules and require them.
You should implement worker threads https://nodejs.org/api/worker_threads.html to make two node process communicate to each other
// first.js
const { Worker } = require('worker_threads')
function runProcess (workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker('./second.js', { workerData })
worker.on('message', resolve)
worker.on('error', reject)
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
})
}
async function run () {
const result = await runProcess('variable value to send')
console.log(result)
}
run()
// second.js
const { workerData, parentPort } = require('worker_threads')
parentPort.postMessage({ received: workerData })

How do I display response data in the front end?

I've made GET requests to the github API:
axios.get('https://api.github.com/users/roadtocode822')
.then(function (response) {
console.log(response.data);
})
I get the response data. This function lives in the app.js file.
Also lives on the app.js file is the following code:
app.get('/', function(req, res){
Article.find({}, function(err, articles){
if(err){
console.log(err);
} else {
res.render('index', {
title: "Articles",
articles: articles
});
}
});
});
I'm able to query data from my mongodb database through the Article.js mongoose model and send the data to my index.pug file.
I want to be able to take the GITHUB response data and also render it in one of my pug view files. I feel like I'm missing some sort of concept in Javascript that's preventing me from achieving this.
Thanks in advance.
To get the Github response as a JSON, just use JSON.parse(). You won't be able to use your .pug template on the front end, however. That template is interpreted on the server side and is sent from server to client as plain old HTML. If you're interested in front-end templating, check out something like handlebars.js.
axios.get('https://api.github.com/users/roadtocode822')
.then(function (response) {
console.log(response.data);
})
from the code above, response.data will be a html content because your server returns res.render.
in the front-end, you should use a tag and form post instead of ajax call like this
Click

Stormpath Custom Data

I requested stormpath user custom data by using
res.render('home', {
title: 'home',
user: req.user.customData,
});
i expected to receive a json object of custom data but instead a url ('https://api.stormpath.com/v1/accounts/WvtGbIH3kJ4rEttVF5r9U/customData') was returned. This page does have the custom data i want on it but i cannot request it using an ajax request as it is a https page. What should I do? Thanks in advance
You'll need to use the "auto expansion" feature of the library, like this:
app.use(stormpath.init(app, {
expandCustomData: true,
});
That will expand the custom data resource for you. By default it's just a link to the resource, as you've seen.
Found the best way to request custom data is to use the getCustomData() method in the route, set the data to a variable and use a get request from the client to request this data as in the sample below:
Server Js
customData = new Array;
router.get("/string", function(req, res) {
req.user.getCustomData(function(err, data) {
customData = data.someKey;
})
res.send(customData) /*Returns Empty Arrray*/
})
router.get("/cdata", function(req, res) {
res.send(customData) /*Sends Actual Custom Data*/
})
Client Js
var customData = new array
$(document).ready(function() {
$.get("/string", function(string) {
/*Tells server to get customData*/
})
$(document).click(function(){
if(pleaseCount===0){
$.get("/cdata", function(data) {
for(i=0;i<data.length;i++){
customData.unshift(data[i])
pleaseCount=pleaseCount+1
/*Custom data is now stored in client side array*/
}
})
}
})
That's what worked for me anyway. I don't know why someone down-voted the question as this is an acceptable way to retrieve other user information such as name and email by using userName:req.user.userName in the render function and rendering this information to a p. tag in a jade page by using p #{userName}

Ajax with node.js/jade

I'm searching for a way to use ajax running on node.js, express and jade as template-engine without routing to subpages. I read this: Node, Express, Ajax, and Jade Example
But this doesn't work for me. I don't want to make a route to a partial part of page, so the user could access the partial page. I just want to serve a convertet jade file in a part of the website.
I think about something like this:
$( ".trigger" ).on( "click", function() {
$( ".result" ).load( "ajax/test.jade" );
});
How could I do this without setting a route in node.js so the user could access the subpage without accessing the whole page.
Thank you for your answers.
What if you send the file as a GET parameter:
var jade = require('jade'),
fs = require('fs');
app.get('/ajax', function(req, res) {
fs.readFile(req.query.file, 'utf8', function (err, data) {
if (err) throw err;
var fn = jade.compile(data);
var html = fn({});
res.send(html);
});
});
and send request like
/ajax?file=test.jade
If you do the things like that you will have only one route.
(Still requires a route but) You could set up a route that only provides a valid response if it is an ajax request, and a 4xx if otherwise
app.get('/path', function(req, res) {
if(req.xhr)
{
...
}
});
req.xhr Express docs.
You could place a jade template (or HTML file) in the public folder on your website, assuming you have it set up.
For example, in the app.js:
app.use(express.static(__dirname + '/public'));
Place the template/file in (or any subfolder):
/public/example.html
Then you can use $.get to load the file, like the link you provided:
$.get('/example.html', function(result) {
$('#test').html(result);
});
I have a problem with ajax call
Server side:
router.get('/user/letterlist', function(req, res) {
// ... some operations
res.render('userLetterList', { title: 'test', rows : rows? rows: null, pageCount: pageCount,itemCount: itemCount });
});
Client side index.jade
extends layout
block content
div(id="userLettersList")
button(type="button" class="btn btn-success")
{success}
script.
$(".btn").click(function(e){
e.preventDefault();
$.ajax({
url: "/user/letterlist",
success: function(data){
$("#userLettersList").html(data) ;
}
});
});
client side userLetterList.jade
table(id="UserLetters" class="table table-striped table-bordered")
thead
....
The problem is when push on the button to load data into the div, it will retrieve and show, but the page redirect to nowhere with a blank page, after some m-seconds.

How to create a ajax POST with node JS?

I am not sure how to use an ajax POST to POST from a Jade Page to Node JS. If someone can provide an example or tell me what I am missing from the script I have, please let me know.
This is the script file:
//Add friends
$('.addContact').click(function() {
$.post('/addContact',
{friendRequest: $(this).data('user')});
if($(this).html!=='Contact Requested') {
return $(this).html('Contact Requested');
}
});
The url I have for a POST on my app.js file is:
app.post('/addContact', user.addContactPost);
I am trying to post true for a click event on the button Add Contact and change it to Contact Requested if the data in the db is shown as true.
This is the jade file:
extends layout
block content
div
legend Search Results
div#userResults
for user in ufirstName
a(href='/user/#{user.id}')
p #{user.firstName} #{user.lastName}
button.addContact Add Contact
The route file is this:
exports.addContactPost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid, {
$push: {friendRequest: req.body.friendRequest}
}, function(err) {
if(err) {
console.log("post2");
return console.log('error');
//return res.render('addContactError', {title: 'Weblio'});
}
else {
console.log('postsuccess');
//alert('Contact added');
res.json({response: true});
}
});
};
If you are posting AJAX request, then you are expecting from JS on client-side to get some response, and react to this response accordingly.
If it would be separate request to another page - then probably rendering whole page - would be actual option.
But as you just need to get response from server and then update your front-end without reloading based on response, then you need to response from server on this POST request with some JSON. And then on client-side, do some templating, use jQuery or some templating libraries on client side for it.
Everything looks good I just think the $.post code is a little off. This might fix your problem.
$('.addContact').click(function() {
$.post('/addContact', { addContact : true }, function(data){
console.log('posting...');
$('.addContact').html(data);
});
...
});
The object I added to the $.post is what is going to be sent to the server. The function you specified at the end is your callback. It's going to be called when the function returns. I think that may have been some of your confusion.
Your node route should look something like this
exports.addContactPost = function(req, res, err) {
User.findByIdAndUpdate(req.signedCookies.userid,{
addContact: req.body.addContact
}, function(err) {
if(err) {
console.log("post2");
res.render('addContactError', {title: 'Weblio'});
}
//assuming express return a json object to update your button
res.json({ response : true });
});
};

Categories

Resources