Getting value from a console.log to html - javascript

The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html.
router.post('/index', function(req, res, next) {
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
$(document).ready(function() {
var output = document.getElementById('cost');
output.innerHTML = toCost;
});
res.location('/');
res.redirect('/');
})
I receive the following error and jquery is loading fine.
$ is not defined
Admittedly this is an over-engineered node/express app. The code snippet lives wrapped in a route file, inside a post request.
How do I get my value onto the html?
Jade layout
extends layout
block content
form(...)
div#cost

The normal way to do this would be as follows:
router.post('/index', function(req, res) { <<< 'next' removed (only needed if using middleware)
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});
Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this:
indexTemplate.jade:
extends layout
block content
form(...)
div#cost #{cost} <<< adds the cost variable to page
Then the value of toCost will appear in the resulting page.
No jQuery is required on the server side.

jQuery is made for DOM manipulations and there's no DOM on a server.
Try using 'jsdom'.
jQuery is made for client side scripting, not for server-side client manipulations.

It seems that you're trying to make changes on client-side from your backend. It doesn't work that way.
You could create a variable on backend for storing calculation result. And get this value by get query from client-side

You're tring to reach DOM (that is on client side) from NodeJS on a server side. It doesn't work that way.

Related

node.js sending client side rendered code to server side like to post request

js and javascript... i getting problem in how send array value from client side .js file to server side app.js into post request.
var = testParamterName=[],testParameterValue=[];
$("#Table1 tbody tr").each(function(rowinex){
// this basically gets the 2 column values that i require
var i=0;
$.each(this.cells,function(callIndex,cell){
if(i==2) //parameter value
{
testParamterName.push(cell.textContent);
} else if(i==3)
{
testParameterValue.push(cell.textContent);
}
i++;
});
i=0;
});
i am getting values from a table using jQuery in a file called test.js
after saving the table values into two array namely 'testParameterValue' and 'testParamterName'
now i want to send these 2 array values to my server side .js file app.js
i used the module.exports = {testParameterValue , testParametername};
but this gives an error saying module not defined..
i have tried searching the web couldn't find the solution to my problem ... the closest solution i found was that .... cannot run module.exports into files that run in the browser.
i have skipped the code where i handled a click event for submit
please help me ...Thanks in advance :)
First of all you need to setup your server-side application with e.g. NodeJS and express. Your basic app will listen on the specific port, like localhost:3000. Then you need to request this URL with your client-side JavaScript code.
This issue is very well explained over here:
How to process POST data in Node.js?

Set Session value using Javascript and retrieving the same using razor umbraco

I have written following code let say in Page 1
<a Onclick="setSessionValue()" href="page2"></a>
<script type="text/javascript">
function setSessionValue()
{
var selectedCarNoideId = "1026";
'<%Session["BannerNoideID"] = "'+ selectedCarNoideId +'";%>'
alert('<%=Session["BannerNoideID"]%>');
}
</script>
And now retrieving session value on other page (Scripting File .chtml) using following code.
<h2>Session-:#Session["BannerNoideID"] </h2>;
In the Page 1 alert PopUp displays "1026" as session value
But In Page 2 tag display following value as a output of session .
"Session-:'+ selectedCarNoideId +'"
Am I missing any thing ?
You're mixing javascript and server-side code in such a way that the javascript isn't being evaluatd as you expect.
The Server side session variable is literally being set to '+ selectedCarNoideId +' as the page is being rendered. Javascript in this case is doing nothing to set the session value.
Although why you're getting the alert message to display 1026 is anyone's guess - is the BannerNoideID session variable being set elsewhere as well perhaps?
If you're trying to save a variable generated client-side with Javascript in the session on the server, you will need to submit it.
One way to do it would be to create a simple MVC Controller (WebAPI by default is sessionless) and then POST the value to it using Ajax or a form post.
Alternatively, you could pass the id through on the QueryString to the next page or something like that - that approach is probably the simplest.
Without knowing more about your setup, workflow and business logic I can't really suggest much more.

Node.js only reloads a json file on server restart although that should happen dynamically

I have a Post-form in my ejs-template that passes one object via Ajax/post without the page being reloaded. The handler in my app.js then saves the data into a data.json. All of this is working perfectly.
My only concern is that node seems to be requiring the json file only once, I have already tried using setInterval() which made no difference at all.
The desired functionality is that the server reloads the data.json after every other submit of my form. Furthermore I have an iframe where the loaded data is displayed. This should happen on the fly therefore without any refresh of the page.
For your above comment socket has nothing to do with it.
To answer your question , you can keep that JSON in memory , creating that object as a global object accessible by every part of code (files).
code example ->
app.js -
global_json = require('../path/myJSON'); //please note that I am not using var here to make it global
//Rest of the code
file1.js -
module.exports = fun(req, res) {
global_json.something = req.body.something;
//global_json accessible in every file
}
Alternative
If this is not the use case, then you can read and write file in every request (from post), although file reads/writes are slow but wont be the bottle neck in case of node.js server
function formpost(req, res) {
var data = req.body;
fs.writeFile('filename.json', JSON.stringify(data), cb);
}
//And same with reads

How do I pass node.js server variables into my angular/html view?

I have this route in my app.js file that starts the server
app.get('/view/:item_id', function(req,res){
var A = 5;
res.render('view_item');
and I have this in my view_item.html:
<p>{{A}}</p>
I want it to display the variable value - 5. If I were using a template engine such as jade it would be easy. I could change that third line of my server code to res.render({A:A},'view_item');
But I am using html as my template engine. My research so far has told me that using a template engine with angular is usually a bad idea, and there is always a way to do it using angular's built in template system. So how do I do this? Do I somehow pass it to the $scope and include like
<script>
$scope.A = {{A}};
</script>
I haven't seen this done anywhere so I don't think its the way to go.
This is a two step process.
First, you need to use a library(server library) like express in node to set the proper routings (REST Services) to respond to your Requests:
Server Side
//app = express();
app.get('/api/:paramID1/:paramID2',function(req, res){
return res.json({ A: 5 });
});
On the client side, you need an ajax call to invoke the service like:
$http.get( "/api/1/abc").success(function( data ) {
$scope.A= data; //from your sample;
alert( "Load was performed. " + data );
});
Please note that when using REST there are different type of "methods" that can be invoked depending on your needs, such as POST, DELETE, UPDATE or the one just mentioned in the example GET.
If you are using Angular you should probably be building a single page app -- this would apply for most of the modern front end frameworks. For SPAs you start out with a basic html file (probably index.html). Then, your framework handles the rendering of everything else. Your server may also emit templates, but it will never render anything itself.
app.get('/view/:item_id', function(req,res){
This shouldn't be rendering anything or returning HTML. Instead, you should be returning data that the front end will use to render -- preferably as JSON.
res.json({A: 5});
Then with Angular you would do something like
$http.get("/view/1").success(function (data) {
ctrl.A = data.A;
});
Your html/template would have something like
<div ng-controller="ctrl as ctrl">
<div>{{ctrl.A}}</div>
Once $http.get completes, ctrl.A is populated.

Accessing Express.js local variables in client side JavaScript

Curious if I'm doing this right and if not how you guys would approach this.
I have a Jade template that needs to render some data retrieved from a MongoDB database and I also need to have access to that data inside a client side JavaScript file.
I'm using Express.js and sending the data to the Jade template as follows :
var myMongoDbObject = {name : 'stephen'};
res.render('home', { locals: { data : myMongoDbObject } });
Then inside of home.jade I can do things like :
p Hello #{data.name}!
Which writes out :
Hello stephen!
Now what I want is to also have access to this data object inside a client side JS file so I can manipulate the Object on say a button click before POSTing it back to the server to update the database.
I've been able to accomplish this by saving the "data" object inside a hidden input field in the Jade template and then fetching the value of that field inside my client-side JS file.
Inside home.jade
- local_data = JSON.stringify(data) // data coming in from Express.js
input(type='hidden', value=local_data)#myLocalDataObj
Then in my client side JS file I can access local_data like so :
Inside myLocalFile.js
var localObj = JSON.parse($("#myLocalDataObj").val());
console.log(localObj.name);
However this stringify / parsing business feels messy. I know I can bind the values of my data object to DOM objects in my Jade template and then fetch those values using jQuery, but I'd like to have access to the actual Object that is coming back from Express in my client side JS.
Is my solution optimal, how would you guys accomplish this?
When rendering is done, only the rendered HTML is send to the client. Therefore no variables will be available anymore. What you could do, is instead of writing the object in the input element output the object as rendered JavaScript:
script(type='text/javascript').
var local_data =!{JSON.stringify(data)}
EDIT: Apparently Jade requires a dot after the first closing parenthesis.
I do it a little differently. In my contoller I do this:
res.render('search-directory', {
title: 'My Title',
place_urls: JSON.stringify(placeUrls),
});
And then in the javascript in my jade file I use it like this:
var placeUrls = !{place_urls};
In this example it's used for the twitter bootstrap typeahead plugin. You can then use something like this to parse it if you need to :
jQuery.parseJSON( placeUrls );
Notice also that you can leave out the locals: {} .
Using Jade templating:
If you are inserting #Amberlamps snippet of code above an included static HTML file, remember to specify !!! 5 at the top, to avoid having your styling broken,
in views/index.jade:
!!! 5
script(type='text/javascript')
var local_data =!{JSON.stringify(data)}
include ../www/index.html
This will pass in your local_data variable before the actual static HTML page loads, so that the variable is available globally from the start.
Serverside (using Jade templating engine) - server.js:
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', ensureAuthenticated, function(request, response){
response.render('index', { data: {currentUser: request.user.id} });
});
app.use(express.static(__dirname + '/www'));
You don't need to pass the locals variables in render call, locals variables are globals. On your pug file call don't put keys expression e.g #{}. Just use something like:
base(href=base.url)
where base.url is app.locals.base = { url:'/' };
Have you heard of socket.io? (http://socket.io/).
An easy way to access the object from express would be to open a socket between node.js and your javascript. This way data can be easily passed to the client side and then easily manipulated using javascript. The code wouldn't have to be much, simply a socket.emit() from node.js and a socket.on() from the client. I think that'd be an effective solution!

Categories

Resources