Pass Data From Node/Express to Front-End Javascript - javascript

I am unsure how this would work exactly, and I am unable to find my answer from searching for it. I am working with a node and express server, and have been passing data to my front end ejs without issues. Now, I am trying to implement charts.js in my front-end, and that requires the data to be in a front-end javascript file. I know that to pass data to my ejs file, I use something like this:
res.render("dashboard", {data: data});
and to display the data in the ejs file, I use
<%= data %>
Now, what I would like to do, is basically the same thing, but instead of passing the data into an ejs file, I want to pass it into a javascript file, while still displaying the ejs file. Right now, I can't seem to figure out how I go from having my data in the express server, and returning it into a front-end javascript file. The flow I am looking for would be something like this:
In node:
data = []:
res.render("dashboard", {data: data});
and then the ejs file is rendered and data is passed into the front-end javascript file that is being used within the ejs file:
let data = <%= (data array passed from the node server here) %>
Of course, this is not the correct way to write the code, but this is the basic logic I am trying to implement.
I am sure this is something simple, but I can't seem to find the answer within my context here. Are there any resources where I can learn to do what I am trying to do? Thanks.

You can't respond to a single request with both an HTML document and a seperate JavaScript file.
So you need to either:
Store the data somewhere and, in a separate endpoint, serve up some generated JavaScript and have a mechanism which identifies which data to serve up when the request is made. (NB: This is stupidly complex. Don't do it.)
Generate the JavaScript inline in the HTML document inside a <script> element. (You'll need to properly escape the data as JS to make sure you aren't subject to XSS).
Output the data into the HTML document (e.g. with data-* attributes or <meta> elements) and read it with static JavaScript.
Again, using a seperate endpoint: Serve up JSON with the data in it and read that with Ajax from a static JS file. (Again, you'll need a way to determine which data to send for that particular request).

Related

What's the best/most efficient way to send data from Rails to JavaScript in a Slim view template?

I have researched how to send data from Rails to JavaScript in a Slim view template, and the most accepted method is to declare a Ruby section on the Slim template to get the data from the controller, and then declare a JavaScript section to store that data into a window variable, and then load the JavaScript pack that's going to use that data.
The data is needed to build a JavaScript snippet that will go in the <head> of our app.
Here's an example of what I'm doing (this is the app/views/layouts/_my-template.html.slim file):
ruby:
myDataFromRails = #my_data.to_json.html_safe
javascript:
window.myData = #{myDataFromRails};
- include_javascript_pack 'my-pack'
The problem with this method is that all the data coming from the Rails backend is available for anyone that inspects the code or types window.myData in the developer tools console, which is not ideal...
Another option will be to query the backend from the JavaScript snippet itself, using an HTTP request, but this doesn't look like an efficient way of getting the data from the backend.

how to send data on file with sendFile in express

I am trying to parse my csv file in server and return back the information after parsing and analyzing the data in csv.
I am not that used to express and i dont know any view engine.
I plan to use
res.sendFile(path.join(__dirname, "/index.html"));
to host my index file.
What are the other way than ajax and view template that can I send data to the index.html with sendFile.
I am sending JSON files from server to client
Any kind of help is appreciated !!!
When a client (such as a browser) makes a request you can respond with one thing.
You can respond with:
The contents of a file as you are now (although you should use the static middleware instead of rolling your own end point handlers (without caching) one-by-one)
A template + some data rendered into a single file (using the view engines you haven't gotten around to learning yet)
Some JSON (typically in response to an Ajax request so the a JS program running in an HTML document get add more data to the existing HTML page)
Something else
If sending an unmodified file is not what you want, then don't use sendFile.

NodeJS & Jade/Pug variables not defined in jade script?

When I pass a variable over to jade, it looks like it works correctly, for example #{myvar} works but, when I try to call it in a script block in Jade, it doesn't load at all. Upon doing a typeof(myvar) in my script block it said that it was undefined at one point but now it doesn't return anything. My code looks something like this:
- typeof(rm120[0].description) <---- Returns string
div#change !{rm120[0].description} <----- Works perfectly fine
div#test
script.
change.innerHTML = "test code" <------ Works perfectly fine
test.innerHTML = rm120[0].description
test.innerHTML = typeof(rm120)
test.innerHTML = typeof(locals.rm120)
all the lines after the first one in script. seems to never load or just get ignored and I'm extremely confused as to why I can't use the objects I passed through from my node.js file in my script block. Any help would be much appreciated!
The script tag in Pug renders text which is sent to the client to run as client side Javascript. As server side variables don't exist on the client, they need to be passed across to the client somehow.
Two possible ways are rendering the variables in Pug or passing the data out via an AJAX call.
Render
Rendering variables into the Javascript is the simplest method to pass data but I tend to keep this limited to very simple, bootstrap data required for the JS App.
script.
let rm120 = !{JSON.stringify(rm120)}
console.log(rm210)
AJAX
Using an API endpoint to pass JSON objects out is more complicated to setup as there needs to be a server endpoint and you start dealing with async requests. As an app starts passing more data, or more complex data, then it's a more scalable method of sharing.
script.
fetch("/api/v1/rm120")
.then(response => response.blob())
.then(body => {
console.log(body)
})
.catch(err => console.log(err))
I assume you're trying to insert the actual value of rm120[0].description on your html file, which you want to run as a script once it's delivered to client side. In which case you need to use #{} or !{}.
If you don't, then the word "rm120[0].description" will be written onto your html file, quite literally. And when it runs client side, there won't be an rm120 presumably.

Html button to send a post request to retrieve information from .json in a table

I have a simple html file that has a button called Display Animal. I have a seperate .json file that has various animals stored in some way. What I am trying to do is on click of Display Animal I want to fetch the information from this json file and display it in a table on the screen. I am using Express, Node, jQuery and Javascript. Note that I am running server that displays the simple html file. I am little unsure of the structure of how to do this? Like in my html file do I have my onClick method there or in my server file? Also, how do I fetch this information? I am trying to accomplish this using GET or POST requests.
Are you using a front-end library (like jQuery or Angular) or are you trying to do this natively with JavaScript?
If the former, there are HTTP request APIs built into each (e.g. jQuery.POST(), or $http). If the latter, you'll want to look into native XMLHttpRequest.
Not a sophisticated answer, but your question is very broad. I'll leave reading the documentation to you.
Create a get service on your backend, with express it would be something like
var app = express();
app.get ('/animals', function (req, res){
// your code to parse and return your list of animals, function (err, data) {
res.end (data) }
That's not 100% working code but gives you an idea how the get will be formatted.
Then you can either use jquery.get () with your button onclick or write out a javascript xmlhttprequest.
Jquery would be easier but for you want to do it yourself there are tons of tutorials on writing a xhr in javascript.
EDIT: I wrote this in response to a get request. If you want to use post it's essentially the same, use jquery.post () as the other answer suggests and instead of app.get it would be app.post.
For data like animals I'd use get, you are only showing information with no need to change it and a unless you are passing sensitive information get will serve your purposes fine.

Alternative to passing Data to JavaScript from PHP?

I have a fairly large Application and I'm currently trying to find a way around having to pass Data from PHP (User Tokens for 3rd Party API's and such) through the DOM. Currently I use data-* attributes on a single element and parse the Data from that, but it's pretty messy.
I've considered just making the contents of the element encoded JSON with all the config in, which would greatly improve the structure and effectiveness, but at the same time storing sensitive information in the DOM isn't ideal or secure whatsoever.
Getting the data via AJAX is also not so feasible, as the Application requires this information all the time, on any page - so running an AJAX request on every page load before allowing user input or control will be a pain for users and add load to my server.
Something I've considered is having an initial request for information, storing it in the Cache/localStorage along with a checksum of the data, and include the checksum for the up-to-date data in the DOM. So on every page load it'll compare the checksums and if they are different (JavaScript has out-of-date data stored in Cache/localStorage), it'll send another request.
I'd rather not have to go down this route, and I'd like to know if there are any better methods that you can think of. I can't find any alternative methods in other questions/Google, so any help is appreciated.
You could also create a php file and put the header as type javascript. Request this file as a normal javascript file. <script src="config.js.php"></script> (considering the filename is config.js.php) You can structure your javascript code and simply assign values dynamically.
For security, especially if login is required, this file can only be returned once the user is logged in or something. Otherwise you simply return a blank file.
You could also just emit the json you need in your template and assign it to a javascript global.
This would be especially easy if you were using a templating system that supports inheritance like twig. You could then do something like this in the base template for your application:
<script>
MyApp = {};
MyApp.cfg = {{cfg | tojson | safe}};
</script>
where cfg is a php dictionary in the templating context. Those filters aren't twig specific, but there to give you an idea.
It wouldn't be safe if you were storing sensitive information, but it would be easier than storing the info in local storage,

Categories

Resources