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
Related
I want to know if the user has logged in or not and then display different elements of the navigation based on the username (login by email and password Not username). However, I have no idea how to deal with session. If php and html is separated in two documents, how can I store the required values using session in php document and then get them using javascript in html document? Or should I use cookies instead?
There are a several approaches to do this.
1) You can make a PHP file which will format your $_SESSION data, and all the other data you want as a JSON string (json_encode function in PHP lang). Then use echo to return it. Then use an AJAX request to get this file from javascript or JQuery, and you will receive the data you want. That's a bad approach for this purpose, from my point of view, because after loading the page you send another request to receive a static data, which will not change on the page like email or username.
2) Better approach: PHP is preprocessor hypertext. You can make an php file and write html tags in it, with php output(example: <div><?=$_SESSION['email']?></div>). Search for more info in google ("php inside html").
3) Much better. In modern web programming world its a mistake to use php inside html because you should think not only about how to make something work, you should think how you will maintain it after 3, 6, 12 months later, too. If you use just php inside html in a big project, then, with time, you realize that your code is hard to read and looks ugly. There are plugins that can make your view more readable and maintainable (Twig, Blade, Volt and others). I recommend you use one of them.
The session is a server side thing, you cannot access it using javascript. You can write an Http handler (that will share the sessionid if any) and return the value from there using AJAX
I would like to give some values to my client (to use them in javascript) from my django server.
I know that I can use cookies, but the problem is that they are kept for all request whereas I need them only once when the client loads for the first time (it is not really a problem).
I could also pass those values to the template to render some html tags with the "data-value-name" properties set the the values (for example <body data-name="joe" data-id="123456">)
Both solutions work fine, but is there a better method?
What I usually do is to create a <script> element where I render the values directly to JavaScript objects stored in local or global variables.
If you have a lot of values you can also consider implementing a view that returns JSON which is requested via ajax from the client.
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,
Just a simple question, I was wondering why some websites have something like "?lang=EN" in their URL after selecting a language? Is it because their html file or folder containing it is named "?lang=EN", or some other code that does this? I'd like to set the URL like that for my website (has 2 languages). Currently I have folder structure like this:
Language selection: D:/media/index.html
EN site: D:/media/en/index.html
CN site: D:/media/cn/index.html
Files for the website: D:/media/site
Thanks.
First of all, anything after the file extension ( .html ) is a server side function.
The ? is a function for PHP and adds variables to the super global GET array ( in the form: ?variable=value&variable2=value2 ) that is directed to from another page and from that point many things can be done with the data.
Sites that use the ?lang=EN are probably programmed to print out the chunks of text needed on the single page in the places and languages required. Though it is possible using this method to redirect to a language specific directory.
Hope this helps :)
That's because they often have a content management system where the content isn't stored in files necessarily, but in a database. The lang=en is a GET variable from the URL that they retrieve in, for example, PHP, to display the correct content. In your case, however, you can just redirect the user if they click EN or CN to the appropriate locations, in your case, /en/index.html and /cn/index.html.
The url you see at the address bar, whatever comes after "?" is called "QueryString" and with libraries on the server side (based on the developing platform that website is made on) you can access the values. For instance the value of "lang" can be equal to "EN" or "CN" etc.
By the way you can have some http handlers to rewrite the requested url and get your parameters through the url that physically doesn't exists. Like the one you mentioned, "http://yoursite.com/en/default.whatever". I myself prefer this way but as you requested you should use some server side libraries to access the query string values and choose the language of the content you wanna send to client.
Also as one solution that once I used, you can also use some translation service (like translate.google.com) client libraries and call it at client side with jquery or even javascript and translate all the texts on page load. Although it's damn fast in action, it has some issues you will see.
Hope it helps.
PHP uses $_GET to get value from variables from the URL.It gets the value from that LANG variable and then it selects all from a file where are stored all the words in different languages or from the database
You don't need to copy every file and then translate it.
Search for php dynamic pages tutorial in your case. I found THIS.
P.S. PHP is one from many ways to do this.
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);