Best way to send data to client js from node.js - javascript

What is the best way to send some data (in the form of a json object ideally) from a node.js server to the client's javascript. I've thought of a couple options, but none of them seem to be very suitable in my opinion. A second opinion, or some other suggestions is what I'm looking for.
Have the server output some code in a <script> tag to set a global variable.
I've used this before, but I dislike the idea of it, mostly because it has potential for XSS, and I think it's bad practice, even if the data being sent isn't defined by a user.
Set a cookie with the data inside it.
This option is a little better, but since the data is likely to change for every page load (at least in my setup), it doesn't really fit since, in my opinion, cookies aren't supposed to be this volatile.
Have the client javascript make an ajax request to the server on page load to request the json file.
This works as well, but it adds a lot of unneeded overhead. 2 requests per page seems unnecessary.
Background:
I have a site with 2 templates: an index for logged-out users, and the main content template.
My server side is built off node.js, express.js, jade, and less.
I am using history.pushState for all my links and crossroads.js for the client's page routing.
I want to be able to send the loaded template, and a user's id / if they are logged in to the client javascript, so it can handle page changes accordingly. Logged out users can view content pages, just without editing privileges, and clicking on certain links should bring them back to the index template.

The <script> tag method is good. If you're worried about other scripts accessing the data then instead of setting a global variable write a function in your client js code that can accept the data.
So instead of generating:
<script>
data = { foo : "bar" }
</script>
generate something like this:
<script>
setData({ foo : "bar" });
</script>
Obviously I don't think I need to tell you that any data you generate should be serialized by a proper JSON serializer to avoid syntax errors etc.

Just enclose the one-time data in <script> tags with type "text/template" or "application/json" and make sure they have IDs. Access their contents with jQuery or standard DOM methods. For shorter bits of data, you can use data-* attributes on key elements.

Instead of Ajax you could implement websockets with either Socket.io or Now (which implements socket.io. These not only allow you to easily pass data back and forth between client and server, but also allows the client to call functions on the server

One way is to use a hidden paragraph to hold a delimited string.
I like to delimit my strings with characters that have no chance of being embedded in my data elements.
My favorite delimiter is:
char delim = (char) 1; // the SOH character of the ASCII character map
The script tag is not a good choice because there are too many delimiters, and there is a likely chance that one of those delimiters is embedded in one of your data elements.
Using JSON has the same problem: too many delimiters.
A hidden HTML paragraph element gets my vote.
Server Side:
Inside a div with id="hiddenStrings" style="visibility:hidden" place paragraphs holding columns and values
p id="delimitedColumnNames"> #Model._ticket.GetDelimitedColumns() /p
p id="delimitedCoulmnValues"> #Model._ticket.GetDelimitedValues() /p
Client Side:
// The leading character is the delimiter.
var delimiter = document.getElementById("delimitedColumnNames").innerHTML.substr(0,1);
var delimited = document.getElementById("delimitedColumnNames").innerHTML.substr(1);
var ticketCols = delimited.split(delimiter);
var delimiter = document.getElementById("delimitedCoulmnValues").innerHTML.substr(0,1);
var delimited = document.getElementById("delimitedCoulmnValues").innerHTML.substr(1);
var ticketValues = delimited.split(delimiter);

Related

Access a cookie that was set on a javascript file, but not on the HTML

I have a script that needs some external information to work with. It fetches this using Ajax requests. So far so good.
However, the script needs some of it's data right from the start. So I have been pondering a few options to supply it with that initial data at page load time:
Simplest: Just have it perform an Ajax request for the data right away. Downside of this is extra latency and more requests than strictly needed.
Ugly: Add a small script fragment at HTML render time that provides the initial data
Bad caching properties: Create the whole JS file dynamically and add the data right then.
Impossible: Something with headers... but unfortunately it seems we can't access them (see e.g. this question). Doing the extra Ajax request is not useful here as in that case we might just as well use option #1.
Something with cookies...
Not tried yet: Create a dynamic 'initial-data.js' script whose sole purpose it is to load the initial data. This would at least only send the data when needed, but it would require all users of my script to include 2 script files instead of one.... Also it will cause an extra request...
I am trying out the 4th option of using cookies to transport the initial data but so far not having any success. What I am trying to do:
When the browser requests the .js file, have the server add a Set-Cookie header with the initial data in it in the response.
In the JS file, read out the cookie.
It doesn't work. It seems I need to set the cookie on the response for the .html instead of the .js for the browser to make it available to the script... That's too bad as it would involve adding the Set-Cookie header to each page, even though it's only needed by that particular piece of JS.
I was actually very happy with the solution I thought I found because it let me send the initial data along with the request for the script only to those pages that actually use the script... Too bad!
Is there any way to do what I'm trying to do using cookies, headers or some similar mechanism?
Do you guys have any tips for this situation?
Background:
I am trying to write a semi-offline application. Semi-offline in that it should continue to work (apart from some functions that just need connectivity) when offline, but is expected to have periods with connectivity regularly. So I'm using local storage and synching with the server when possible.
To be able to have the client generate new items when offline, I am including an ID generator that gets handed out ID blocks by the server, consuming them as it generates ID's. The data I was trying to send to the script in a cookie is the initial list of ID blocks and some settings and looks like this:
/suid/suid.json:3:3:dxb,dyb,dzb
^ ^ ^ ^
url min max blocks
Where:
url = path to JSON for subsequent Ajax requests
min = minimum amount of ID blocks to keep in local storage
max = maximum amount of ID blocks to keep in local storage
blocks = comma separated list of ID blocks
The ID blocks are encoded as sort-of Base32 strings. I'm using a custom formatting schema because I want 53-bit ID's to be as short as possible in text format while still being easily human readable and write-able and URL-safe.

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,

How to dynamically create css/js/html files and serve back at runtime with ASP.NET MVC

Ok, perfect examples: tryIt Editor (w3schools), jsbin, jsfiddle. I want a user to type css/js/html into different textareas, hit a magic button and poof, the output's displayed in an iframe.
Code examples are appreciated but I'm more after answers to how to go about it than exact implementation. For example, I can easily send the js / html / css as strings to the server. Then dynamically create files for them. But then what?
I want to have these files exist merely for the POST & GET. I dont want to remake a jsfiddle, I want to quickly show a user what output they have, not save it for later. So I dont want these files saved to memory. I want them sent to the user, and if they refresh the page then it's gone.
Is the idea of creating files (and removing the old ones each update) a good idea?
Should it all just be done client-side in javascript?
If using files is the correct method, how can I serve them up? I'm thinking create a file to a temp folder on the server, then POST the link, then send a DELETE request after 300ms with a unique ID + salt, which deletes the temp file if it still exists. But this is far from ideal I can think of a few issues immediately
Any server-side action method can technically return any kind of response. So instead of thinking about files, think about response types. Namely:
text/html
text/css
application/javascript (or maybe text/javascript?)
So you'd need at least three action methods. Pressing the "magic button" can, for example, reload a frame (with a POST request which includes the HTML/CSS/JS inputs) which:
invokes the action method which returns text/html, which itself:
includes standard tags in the head node which reference the routes for the CSS and JavaScript "files" (which aren't really files, just action responses)
One handy way to return custom responses from the action methods would be with the ContentResult type:
return Content(htmlText, "text/html");
Or:
return Content(cssText, "text/css");
So your server-side code can, for example, take the CSS text from the client-side and just echo it back like that. (Beware of various attacks, such as XSS. This simplistic implementation isn't likely ideal, but should get you started.) The only one you'd really need to wrap in any custom text would be the HTML response, where you can just statically define the HTML server-side and put the user-input HTML in just the body element.
So just thinking out loud, if the POST request for the frame/iframe consists of the three values, then the basic HTML server-side action might look like:
public GetHTML(string html, string css, string javascript)
{
// temporarily store the css somewhere server-side
// temporarily store the javascript somewhere server-side
// build the html response from static dressing around the user-input html
return Content(htmlString, "text/html");
}
The CSS/JS are stored in a temporary server-side location, possibly utilizing session state or any built-in temporary storage mechanism. After the above action returns its response, the browser will request the CSS/JS actions from the tags in that response, those are simple enough:
public GetCSS()
{
// if the temporary location (session?) has a css value
// get that value
// else
// get a default, likely empty value
return Content(cssString, "text/css");
}
// repeat for the javascript content

How to pass array as a parameter to a plsql procedure through javascript

I am calling a plsql procedure from window.opener.location.href, I want to pass an array as a parameter to this procedure.
window.opener.location.href="dt_bulk_test_pkg.pc_bulk_test?ps="+frmresult.ps.value+
"&p_step="+frmresult.p_step.value+
"&p_year="+frmresult.p_year.value+
"&p_quarter="+frmresult.p_quarter.value+
"&p_diagnostic_type="+frmresult.p_diagnostic_type.value+
"&p_overwrite="+frmresult.p_overwrite.value+
"&p_company_id="+v_comp_id;
v_comp_id is an array.
PL/SQL is a database technology, Javascript is an in-browser technology (unless you're doing server side JS with node or Rhino but you are not). The browser can only communicate with web servers. So from the point of javascript, you're not calling a stored procedure, you're calling a web-server that you must have running somewhere that calls that stored procedure.
How exactly arrays are represented is up to the server-side language/web-framework, but a fairly standard approach is that taken by jQuery's $.param method. For example, opening up the console on this site I can do this:
> $.param({example: [1,2,3]})
"example%5B%5D=1&example%5B%5D=2&example%5B%5D=3"
Words of warning.
Exposing database stored procedures directly via HTTP is not only bad design, but likely a crazy-bad security risk.
Embedding parameters in a url means you are using an HTTP GET request. GET requests are meant for resources that do not affect the state of the server so be careful that your stored procedure only gets data, not changes it. The danger is that someone could put that url in an email or even an img src tag on a webpage and people would hit that url simply by clicking a link or visiting a web page.
All parameters should pass through url encoding. Like I mentioned, jQuery.param will do this.
You are likely exposing yourself to XSS attacks as well.
I know that this is an old thread but I landed here so I guess others will.
It is quite possible to pass arrays to PL/SQL via a URL and it is explicitly supported, not a dodgy hack. Link to Oracle doc
You declare the PL/SQL input parameter as a table of varchar2. Then you pass the same parameter name repeatedly in the URL.
1/ Example PL/SQL source:
CREATE OR REPLACE PROCEDURE test_array(
p IN dbms_sql.varchar2_table )
AS
BEGIN
FOR i IN p.FIRST .. p.LAST
LOOP
htp.p(p(i)||'<br>');
END LOOP;
END test_array;
*2/ Example URL to invoke it: - substitute XXXXXXXXXXXXXX with your own setup *
http://XXXXXXXXXXXXXX/test_array?p=first ele&p=second ele
3/ Output
first ele
second ele
You can pass in as many elements as you want, I just used 2 for this example.
If your data type is not varchar2, capture them as varchar2 from the URL anyway and convert them to numbers etc inside the pl/sql.

i18n in javascript using .properties file

I'm developing a web application with JSF, so I use a Java Properties File (i.e. resources_es_CO.properties) to localize strings for the application and this is working OK.
Mi question is: how can I call localized strings in this kind of files from my javascript validations so alerts show those localized strings to user?
Thanks in advance.
What I do is to send the messages out as part of the page, dropped into hidden <span> tags with "id" values made from the property names.
Alternatively, you could write an Ajax-called action and fetch the properties dynamically.
To do an ajax callback, you'd have to implement a server-side action that would understand something like the property key. The server would just apply the localization (ie look up the property in the locale associated with the session) and then return the string. Alternatively, you could implement a service that'd return a whole set of properties, maybe on a per-form basis, or grouped according to some convention of property names (like, "return all properties that start with 'validation.addressForm'")
The simplest case would look something like this with jQuery:
$.get('/fetchProperty', { property: 'firstNameMissing' }, function(propValue) {
$('#errMsg').text(propValue);
}, "text/plain");
Other frameworks provide similar ajax tools, or you could do the XMLHttpRequest yourself.
you could go to server with an ajax call and send alert texts from server to client and show it. or you could put messages to your page when your jsp's being rendered. both is ok. if you can change language without refreshing the page you probably want to make ajax call. if you can not , putting messages in javascript variables will be easier

Categories

Resources