I have a PHP application that makes extensive use of Javascript on the client side. I have a simple system on the PHP side for providing translators an easy way to provide new languages. But there are cases where javascript needs to display language elements to the user (maybe an OK or cancel button or "loading" or something).
With PHP, I just have a text file that is cached on the server side which contains phrase codes on one side and their translation on the other. A translator just needs to replace the english with their own language and send me the translated version which I integrate into the application.
I want something similar on the client side. It occurred to me to have a javascript include that is just a set of translated constants but then every page load is downloading a potentially large file most of which is unnecessary.
Has anyone had to deal with this? If so, what was your solution?
EDIT: To be clear, I'm not referring to "on-the-fly" translations here. The translations have already been prepared and are ready to go, I just need them to be made available to the client in an efficient way.
How about feeding the javascript from php? So instead of heaving:
<script type='text/javascript' src='jsscript.js'></script>
do
<script type='text/javascript' src='jsscript.php'></script>
And then in the php file replace all outputted text with their associated constants.
Be sure to output the correct caching headers from within PHP code.
EDIT
These are the headers that I use:
header('Content-type: text/javascript');
header('Cache-Control: public');
header('expires: '. date("r", time() + ( 7 * 24 * 60 * 60 ) ) ); // 1 week
header("Pragma: public");
I usually load the appropriate language values as a JavaScript object in a separate file which the rest of my code can reference:
var messages = {
"loading": "Chargement"
}
alert(messages.loading);
The language library will be cached on the client side after the first load and you can improve load efficiency by splitting values into separate files that are loaded based on context: e.g. a small library for public operations, an additional one behind a login, etc.
What you are looking for seems to be AJAX (client and server exchanging asyncronous requests using Javascript).
If you're looking for something ready-made, take a peak at Google Translation AJAX APIs.
I have never personally had to do this, but my first guess would be to reference a third party library. I believe the Google AJAX API might have just the tool to do this, and since the library is through Google, the javascript file will not be downloaded from your site.
Try digging through the following site for a bit: http://code.google.com/apis/ajaxlanguage/documentation/
Let me know if that helps you out. I might be interested in implementing something similar for the website I manage.
Good Luck,
C
I like Pim Jager's answer, and have done that myself. If you don't want to have the PHP generate the JavaScript for you (say, for performance reasons), you can have a master copy of the JavaScript libs, and when they change, run a translation program to generate a version of each lib for each language. Then just have the PHP put the right version for the current user in the script tag it sends.
I worked on a system that needed both heavy localization and heavy branding for different customers. What we did was anything that got sent to the screen had a unique macro, like [3027] (or something like that). Then we had a bunch of locale and branding files that had entries for each macro code, and the text to substitute for each macro. A program would loop through all the source files and all the languages and make the substitutions.
We found we also needed some functions for localization, for monetary amounts, dates, times, etc. It all worked pretty well.
We found we needed one more important thing: A tool to go through all the language files and make sure they all had all the necessary codes. Big time saver.
Related
I am working with asp.net mvc. I note when calling controller actions that return a view via javascript, the html markup returned is not minimized - it includes whitespace etc. Therefore the response size is larger than what it should be.
Is there a way to minimize the response from calling a controller action from javascript?
You might want to look into creating a custom filter to be applied to responses that you want to minify. A technique for this is given in this answer or in this blog post, though you will need to be sure that your implementation of the minification (removing whitespace) does not inadvertantly mess up your code (for example, if you have a javascript content, removing all newline characters can result in all of the following javascript being included in the comment, per this comment).
To this end, it may be worthwhile to use the C# port of Google's htmlcompressor library as a guide for minifying your html.
Of course, you can also just turn on gzip compression on the web server (as Justin points out in the comment below), and get the benefits of compressed output without the headache of implementing (and maintaining) what I detail above.
Note: this may not be worth the effort. A few extra spaces and newline characters in the file that is being sent down the wire will probably not amount to very much space. Even if you save a few KB (which may not even be the case), the increase in performance will most likely not be noticeable. You will however notice that when you try to look at the source of your html in order to debug any issues that you have on the client side, it will be extremely hard to read (spaces and new lines are pretty important for readability).
Doing server side rendering of HTML templates I find myself using Java's Locale class (via various helper functions) to render language codes (ISO 639-1), script codes (ISO 15294), and country codes (ISO 3166) as their name (i.e. "en" -> "English") in a manner that respects the current user's selected locale.
Now, moving some stuff to client side rendering (with Angular JS), I'm a bit unsure of how to approach this. Doing the code-to-name conversion on the server side and sending locale-aware JSON is one option, but it would add quite a lot of complexity to how various bits of data get JSONified (by having to pass the locale through lots of layers of functions, mainly.)
On the other hand, I can see how a full-on client side version of the Java Locale class would involve sending lots of data to the client, most of which wouldn't get used most of the time.
Are there any emerging best-practices for doing this kind of stuff with largely single-page apps, or any super libraries that would solve my problem in well fell swoop?
I am not sure this is the "best practice", but I have also developed a single-page app where I loaded a JSON array with useful JS data on load with ajax. That seemed like the best solution to me if the data is not used right at the beginning of the page.
Otherwise you could just add this script at the end of every page, if you don't mind embedded javascript:
<script>
function get_locale(){
return JSON.parse(/* render JSON.encoded data from server here */)
</script>
Sorry if this not really a definitive answer.
G'day All,
I am pulling my hair out, getting headaches and my eyes hurt. I have been hither and thither and I seem to get whither.
This will be my first experience with xml and would really want to get this working. It is a large file. Well large in my eyes +-5mb. I can not imagine that this file would be loaded into memory to process. Users will get a bit peeved with this.
Basically we are using a 3rd parties site to do our ecommerce. So we have no access to the database other than via the admin area.
What we want to do is make sure that there is no stuff ups when it comes to addresses. Therefore we got this xml file put together listing all postcodes with areas and states:
<?xml version="1.0"?>
<POSTCODES>
<PostCode id="2035">
<Area>2035 1</Area>
<Area>2035 2</Area>
<Area>2035 3</Area>
<State>NSW</State>
</Postcode>
<PostCode id="2038">
<Area>2038 1</Area>
<Area>2038 2</Area>
<Area>2038 3</Area>
<State>NSW</State>
</Postcode>
<PostCode id="2111">
<Area>2111 1</Area>
<Area>2111 2</Area>
<Area>2111 3</Area>
<State>NSW</State>
</Postcode>
</POSTCODES>
Someone suggested SAX but suddenly died when asked how? The web is not helping unless I am not looking properly. I see a lot of examples. Either they do not show how to read the file but rather do it from a textarea or the example is in java.
What do we want? User enters a post code of 2038. We want to go to the javascript with that data and have returned to us all the suburbs that full within that post code.
Anyone out there that can please tell me what to download and how to use it to get what i need?
Please, please, please. It is hard to see a grown man begging and crying but I am.
Sounds like you want a script on the server which will suggest suburbs based on the users postcode selection? You could use jQuery's ajax functionality to do this.
You might also be able to use jQueryUI's autocomplete control to parse XML and make suggestions: http://jqueryui.com/demos/autocomplete/#xml
It's also possible to do this entirely in javascript without any script on the server side, but it would be pretty slow at loading if the XML file is 5MB. You might be able to get a significant reduction in file size thought by gzipping it before transmission from the server.
If you need to parse this in Javascript, you can use jQuery.
http://www.switchonthecode.com/tutorials/xml-parsing-with-jquery
For years I've been reading about XML and I have just not quite grokked it. Most documents I see about it simply explain the syntax (extraordinarily easy to understand) and say that it's portable: I've worked with Unix my whole life so the idea of putting things in plain text to be portable is hardly revolutionary. My specific question is that I have a document (my CV) that I would like to present to web visitors in several formats: as a webpage, as a pdf, or even as plain text. Is XML and Javascript the right approach to take?
What I need is for the document to be easily editable, conversion easy and just easy general upkeep. For example, when I publish a paper, I'd like to take less than five minutes to add the info and then have everything go automatically from there.
Give me your opinions: I also use LaTeX compulsively, so my current approach has been just to have my CV in LaTeX and to convert it to a web-page using LaTeXML. However, I sorta have the feeling that with everybody jumping up and down about XML and Javascript, that there might be something good to learn about it.
I would also like to simplify maintaining my homepage by not duplicating the same footer for every single page that I set up.
Thanks,
Joel
Edit: I'll also take any book recommendations!
I think this is a slight misunderstanding of the combination of JavaScript and XML.
XML, in and of itself is an excellent means of representing data. It's largely human-readable, and easily parsed with libraries in nearly every programming language. That is the main benefit of XML.
Using XML with JavaScript is certainly a solution, but I think it's a matter of the question you're asking. JavaScript can parse XML, and allow you to obtain and manipulate data from your XML document. If you want to grab data from a server without reloading your HTML page (synchronously or asynchronously), then using JavaScript and XML is a valid way to do that.
If you want to, however, display your XML as a webpage, you would likely be better off using XML and XSLT [wikipedia], or perhaps PHP and XPath, to transform the document into browser-readable HTML. On the other hand, you could use nearly any language to convert the XML to a plain-text file, rich text file, or store it in a normalized database.
To sum up, XML is a great way to store data, because it can be used in so many different ways, and by so many different languages. It's an answer to many different questions; you just have to figure out which questions you're asking.
To elaborate on my comment
The transformation to whatever output you desire is depending on how you store your CV on your server and whether you have the possibility to process it on the server. If you store it in XML, you can transform it to desired (binary) output using server based tools - that would for php be pdf and word (on windows server platform) for example. XML would be interesting from a mark-up point of view since it would make it clear where the table of contents, headers, lists of experience and so one would be found.
JavaScript cannot transform something into PDF or word, that has to be done on the server. What javascript can do is to get a text from the server in XML or JSON using AJAX and manipulate this into what the user sees on the screen. For XML that can be done with XSL(T) too. If you want for self-education purposes to use JavaScript, JSON is very nice since it is in my opinion more readable than XML and it creates a populated javascript object with the least work.
Footer in javascript: in the page have
<script type="text/javascript" src="footer.js"></script> and in footer.js, you can for example do
var footerText = 'Here goes whatever you want';
document.write(footerText);
Comparison between XML and JSON
I've got a webpage with browser-side XSLT transformation up and running for years. It's a playground, only some words in german. See how easy it is to build this on heese.net/test. You can switch between "Beispiel" (=Demo) and XSL. The sourcecode of the page in the iframe is the XML. You can do this serverside with 3 lines of PHP-code.
On Javascript: you can use it with XSLT and I show this on my site, but it can't interact. First the XSLT builds an HTML page out of your XML data and after this job is completely done the Javascript in the resultig HTML document begins to work.
Parsing XML with Javascript is a different task.
I use DropBox and I've had some trouble reaching to my files from other computers:
I not always want to login to anything when I'm in a public computer, but I like being able to reach my stuff from wherever I am.
So I've made a simple application that when put in the public folder, ran and given the right UID, creates (still in your public folder) an HTML of all the content in the folder (including subfolders) as a tree of links.
But I didn't risk loading it anywhere, since there are slightly private things in there (yes, I know that the folder's name is "PUBLIC").
So I've came up with the idea to make it a simple login page, given the right password, the rest of the page should load. brilliant!, but how?
If I did this by redirecting to other HTML on the same folder, I'd still put the html link in the web history and the "url's accessed" history of the administrator. So I should generate itin the same page.
I've done it:
alt text http://dl.dropbox.com/u/3045472/validate.png
And currently the page is a textbox and a button, and only if you type in the right password (defined in the generator) the rest of the page (with the link-tree) loads. The fault is that everything (password, URL's) is easily reachable through the source code.
Now, assuming I only want to avoid silly people to get it all too easily, not make a bulletproof all-content-holding NSA certified website, I though about some ways to make these information a bit harder to get.
As you may have already figured, I use a streamwritter to write an html file (head, loop through links, bottom), then it's extremely configurable, and I can come up with a pretty messy-but-working c# code, though my javascript knowledge is not that good.
Public links in DropBox look like this:
Summarizing: How do I hide the URL's ande the password to show them (MAINLY the password, of course) in my source-code so that no that it should require some effort on reading ?
P.S.: It's not that personal, if someone REALLY wants it, it could never be 100% protected, and if it was that important, I wouldnt put it in the public folder, also, if the dude really wants to get it that hard, he should deserve it.
P.S. 2.: "Use the ultra-3000'tron obfuscator!!11" is not a real answer, since my javascript is GENERATED by my c# program.
P.S. 3.: I don't want other solutions as "use a serverside application and host it somewhere to redirect and bla bla" or "compress the links in a .RAR file and put a password in it" since I'm doing this ALSO to learn, and I want the thrill of it =)
Update 1:
The one answer so far gives a perfect way (according to this question) to hide my password.
Now I want a good way to hide the URL's, maby a code snippet of the example URL I gave being composed, and if it's too tricky, maby how to generate it in C#, or anything ?
Update 2:
I thought about maybe making three "obfuscating methods" and choosing them randomly in the runtime. So anyone who figures out how to read one XML, could only read about one third of them, and maybe having a hard time finding the other rest of this third..
Update 3:
Just thought about REGEX, the URL could be neatly crowded by dummy not-url-allowed characters added randomly that would be removed by something like:
regex.replace(url, ^[^\w\d/:-\.%]+$,"")
So the nosy dude should have to be pretty advanced into programming somehow, eh? could anyone tell me if it would work or not ?
Well, as it seems you already know, this is a rather poor choice of security mechanism, but if you insist...
Don't store the actual string in the source. Store, for example, its MD5 hash. Then, when the user types in a password, compute its MD5 hash and compare it with the expected one.
Check out:
MD5 in JavaScript
MD5 in C#
To elaborate on miorel's idea, you can also encrypt the whole page, using password as a key. Basically, encode all content into one big string, ask for the password and decrypt that string. If the password is wrong, it will show loads of rubbish, that is it. Like
content = "encrypted string"
function decrypt(str, key) { your algorithm of choice here }
document.write(decrypt(content, prompt('Password?')))
The only thing you need is a decrypt implementation in javascript - but that's easy to google out, for example here or here.
This also renders the separate 'login' page useless.
Granted, this is akin to asking how you can strip in public without people seeing you, but given that, I'm assuming that the password you are trying to store is the one to DropBox. I suppose you could obfuscate the password and store it in a cookie. That would at least prevent someone from simply viewing the source to see the password, but obviously wouldn't stop someone running something like Fiddler and seeing it.
[snipped server side suggestion]
EDIT: To munge the Urls, why don't you simply build the urls on the fly and have the links call a javascript function to get the url? Your server-side code would populate an array in this function with obfuscated urls and the calling code would simply pass an index into the array. Thus, on viewing the source, there would be no instances of "http" anywhere other than static unsecure links.
ADDITION Ok. now that I have a better bead on the problem, it is easier to devise solution. There are libraries for doing encryption on the net in javascript (e.g. http://point-at-infinity.org/jsaes/) but the problem comes down to key management. Since its javascript, it is going to be public but there are hoops you can devise to make it harder to determine the key. In general, those tricks involve indirection. For example, store a lengthy stream of random characters (e.g. 40-50 or more) that is generated by your C# code and stored in the HTM file. In addition, the C# code would would store into your javascript function an array numeric values that represent pointers into the long stream of text that were used by the C# code to encrypt the passwords (or just the whole url).