Passing variable from jade file to javascript file - javascript

I am making a node express app. I am trying to pass a value from jade to a javascript file.
On the server side I am using:
res.render('index', { title: 'Title', test: 1 });
In my index.jade file I have the following:
script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.js')
script(type='text/javascript', src='./javascripts/ui.js')
script(type='text/javascript', src='./javascripts/handle.js').
var data = !{test}
block content
h3= title
In my handle.js file I have
$(function() {
console.log(data);
});
On the console I get a message saying data is not defined. How do I pass the value of test from the jade file to the javascript file? Currently test is just an interger, but eventually it will be an object which contains a lot of properties.
How do I properly pass the value from the jade file to the javascript file?

That will only work for literals. For objects you can do this:
var data = !{JSON.stringify(data)};
As for the showing undefined part, check if its getting properly set and it is the correct variable.
Make sure you are loading in correct order:
script(type='text/javascript')
var data =!{JSON.stringify(test)};
script(src='./javascripts/handle.js)

Related

Local host interrupts data read with getJSON

I've saved a JSON file in my local direcotry. The current path is "application/data/file.json". I'm using getJSON to read this file but I keep getting an error saying "jquery-3.6.0.js:10109 GET http://127.0.0.1/data/history.json 404 (NOT FOUND)".
I'm trying to get the data from the json file as a part of building web application. In the html script, I set something like this and I wonder if the host url is interrupting the data read with JSON.
{% block script %}
<script type="text/javascript">
var host_api_url = "{{host_url}}"
</script>
<script src="static/script.js"></script>
{% endblock %}
I'm using json getJSON to read the data from the json file and create some html components in my js script like this:
$.getJSON("application/data/file.json", function(data) {
$.each(data, function(key, value) {
$("<div />", { "class":"group" })
.append($("<p />", {name:"title"+i, id:"title"+i, text: key }))
.appendTo(".output");
$("<div />", { "class":"group" })
.append($("<p />", {id:"content"+i, text: value }))
.appendTo(".output");
i++;
})
});
Is there any way to get the data from the local directory and resolve the error I specified above?
Just to be sure, you need to serve that file.json through a web server, in your case running on 127.0.0.1 since jQuery.getJSON() is using a HTTP GET request - it will not read a local file directly.
https://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success
The error message indicates that you likely misplaced the file in the wrong directory.
Note that you cannot read arbitrary local files from a browser environment programmatically (due to the browser sandbox principle).
If this JSON file is an end-user supplied file, you can ask the user to
drag and drop it into the browser and then use the FileReader API to read that file, see https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API or
ask the user to select a local file through an <INPUT> form element.
Starting point: https://developer.mozilla.org/en-US/docs/Web/API/File
Once you have the file read in, use data = JSON.parse(textcontent) to parse it as JSON and retrieve the JS object data.

Cannot pass server object from one jade file to another jade file

I have just started using jade and node. I am passing an object from node to jade template (parent.jade) and including the same jade file (parent.jade) to another file (child.jade). it is depicted as follows:
Node part:
res.render('parent.jade', {data: mydata});
Then in parent.jade I am receiving the data correctly:
doctype html
html
head
title parent
script(type="text/javascript" src="/resources/file_javascript.js").
var data_from_node = !{JSON.stringify(data)}; //getting the data in javascript file
body(data-title="parent")
div#header(class="wrap")
include header.pug
ul#list(class="nav nav-tabs")
footer(id="footer" class="footer")
include footer.pug
In child.pug I am including the parent file but could not get the data object. I have tried everything but nothing is working here I am including it in the following way:
doctype html
html
head
title child.pug
body(data-title="child")
div(class="wrap")
include parent.pug //here I am including parent.pug getting the content right
div#mydiv(class="tab-content")
include table.pug
footer(id="footer" class="footer")
include footer.pug
script(type='text/javascript').
var data = !{JSON.stringify(data)}; //getting null here
script(type = "text/javascript", src = "/resources/file_javascript.js")
Is there any way to get the "data object" in child.pug from parent.pug because I am getting null in child.pug?
Unfortunately not. When you call res.render in Node.js, the context variables you pass to that template are only remembered while that template is being rendered. If you want to let child.pug have access to that variable, you must actively pass it to that template, as well (when you call res.render("child.pug", {...})).

Pass html to an index template and save into a javascript variable with nodejs and hoganjs

I have hongajs in my nodejs app, and I need to pass an html content to an variable into my index.html file so, I try with this.
I have on nodejs this fragment:
res.render('index.html',{
note:{
title: doc.title,
body: doc.body
}
});
And in my index.html this:
<script>
var parseNote = '{{note.body}}';
</script>
Of corse I tryed with {{{ and JSON.stringify, and many other javascript function, but any seems to work.
Some ideas?

Nodejs, Express How to pass variable to route and use it in external JavaScript file?

I am working on a web app using MongoDB Express NodeJS stack and in one of the routes I am getting array from database and then passing it to route.
Code:
app.get("/badges/new", function(req, res) {
Colour.find({}, function(err, foundCoulours) {
if(err){
console.log("error: "+ err);
res.redirect("back");
} else {
res.render("badges/new",{foundCoulours:foundCoulours})
}
});
});
All done easily but here is a bit that I am stuck at the moment: I want to use jQuery to add elements onto the page depending on the result that came from server. I can do it using script tag and in-line JS on the ejs file without any problems but what I would like to do is to use external JavaScript file so my ejs wouldn't look as massive just with <script src="public/foo.js"></script>.
Question: Is there a way to pass foundCoulours to "public/foo.js" file after it was passed to route? Or maybe I can pass it straight to "public/foo.js" file from the request route.
You can sequentially load the scripts. As below:
Jade
body
script(type='text/javascript').
var foundCoulours= #{foundCoulours}
script(type='text/javascript', src="foo.js")
EJS
<script>
var foundCoulours = <%= foundCoulours>
</script>
<script src="public/foo.js"></script>
Explained:
As we are loading foundCoulours variable in global scope, it is directly accessible in foo.js, as it is loaded after the variable is initialized.

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