Access jQuery Controls on Server Side? - javascript

Is there a library or framework built for invoking jQuery / Javascript functions from the server side?
For example, say I'm using a jQuery UI datepicker control on my page. The datepicker's format (e.g., MM/dd/yyyy) is configurable on a per-user basis. In this scenario I'd have to retrieve user preferences on the server, record the user-chosen format in a hidden control, send the HTML page to the client, and finally extract the format from the hidden control on the client side. Does any library exist that facilitates this long-winded process?

I like to use custom attributes for this sort of thing.
<asp:TextBox runat="server" id="myDatePicker" ClientIDMode="Static"
format="MM/dd/yyyy" />
Render the attribute when you render the page based on the user settings, then the client code can just grab it whenever it's needed and apply as appropriate:
var format = $('#myDatePicker').attr('format');
I sometimes use a simple infrastructure for this purpose which can JSON+base64 encode objects to include in a generic "data" property, then unwind it at the client, to add more complex information to a control.
In other situations I just grab the settings when I need them from the client using a service called through ajax, but this way is more efficient, if you already know what it is when the page is rendered.

You'd need to incorporate some sort of server side scripting language such as MySQL/PHP to pull the users preferences, then it shouldn't be too hard to bundle in. You would just need to make the storage "dynamic" in that it accepts a wide range of date formats, or convert to a more standardized format.
Until I know what languages you are using, or some sample code, its hard for me to answer.

Depends on how your site and page is setup. But, if you are storing the user's selected date picker format in a cookie or session variable you could expose this value through a string property on the page (e.g. DatePickerFormat) and then make the jQuery datepicker dateFormat dynamic something like this:
$(document).ready(function() {
$('#idOfDataPickerControl').datepicker('option', 'dateFormat', '<%=DatePickerFormat%>');
});

Related

Define in Smarty the format to be returned by AJAX

I have a html form in a Smarty template. A select in the form is populated via AJAX. I would like to specify in the Smarty template, the format to be returned by the AJAX-call. This way I can use the same request-url for different purposes. For example if the select contains users, sometimes I might be interested in knowing the user's email address (format: "{$Option->GetName()} ({$Option->Email})"), and other times the user's organisation (format: "{$Option->GetName()} ({$Option->Organisation})").
I have a few ideas of how to achieve this:
Store the format in html/js in the template. Then the AJAX-call can send the desired return-format along with the request. Drawback: A malicious user can change the format in the request, which might be a security issue.
Pass along the entire $Option object, and do the formatting using JavaScript. Drawback: Cannot use the PHP object's methods, such as $Option->GetName().
Store the format in a separate template file, and reference to this file in html/js and send along with the AJAX request. Drawback: The reference to the template file can be changed by a malicious user, but probably no damage can be done. This approach requires extra template files, and the presentation logic will be spread over different files.
Create a Smarty plugin that automates the process of item 3. Then the presentation logic will not be separated. Drawback: The reference to the template file can be changed by a malicious user, but probably no damage can be done.
Do anyone have any other/better ideas, or any experience with doing something like this?
I don't think you need to set some format. You can create a javascript function with 3 parameters. The <select> tag identifier, the name of the key used for options value, and the key name used for options text. The function will make the ajax request. That way you can call the function with settings you need for particular situation.
Further details depend on your current code.
I ended up using option 4, and I'm very happy with the result.
If anyone come across this and need information on how I implemented it, just post a comment, and I'll try to explain.

"Null" HTML DOM Element?

I'm writing a framework which uses javascript/html as the client and it-doesn't-matter as the back end.
From time to time I have a need to store data in the HTML DOM. Ideally I'd like to store the data against a DOM element, but I want this element to have no UI impact.
At the moment I'm thinking I'll use a <span> with no text content and decorate it with attribution so that my framework can pick up that it is a data container and behave appropriately.
Is there a better choice? (For the avoidance of doubt, I know there are other ways I could do things - I'm not interested in these, purely in what the best HTML element to use to contain data without having a UI impact).
Edit (explanation of architecture):
I've created a server-side technology which is based on top of a generic reporting engine I've previously created. This server-side thing essentially works as a web-server - this might seem like an unusual choice to make but, given organisational constraints, it's the best choice - for the sake of argument, assume this is true. One of the things I need this system to do is to generate dynamic forms to capture data which is in a tree-like form. This has been fine and has worked well - my question is because when a sub-form is hidden (for example, the user has made all required decisions in a given sub-section of the data), I destroy the data capture elements - if the form is embedded within a parent form which needs access to the data captured in a destroyed sub-form, I need a way of embedding the data into the DOM so it can be collected to be passed back to the server. The requirements are a lot more complicated that this, but it'll take far too long to detail them all.
Well (and for the avoidance of doubt), the HTML elements are not supposed to store data. If you really want to, use the <input type="hidden"> element.
For your purpose, I recommend (in that order) using localstorage or cookie or web database.
here are some resources :
localstorage : http://diveintohtml5.info/storage.html
cookie : http://www.the-art-of-web.com/javascript/setcookie/
web database : http://www.tutorialspoint.com/html5/html5_web_sql.htm
As JLRishe pointed out, if you need, for whatever reason, a text node storage, then span is a good choice as div is (and as lot of elements are as long as you display: none them).
You could just create javascript objects...
var myData ={
property1:"aaaaa",
property2:500,
property3:{morestuff1:"AAA", ... },
property3:["list1", "list2", ... ],
....
}
Easy to access and easy to manipulte within the DOM if you need.
No UI impact.... (no render)
The obvious choice here is to use HTML data attribute. If you have a table and want to store info about the table that is not shown to the user - you could just:
<table id="mytable" data-id="2000" data-rows="20" data-whatever="whatever">
You could then get it with jQuery easely with:
$("#mytable").data('rows');
Which would give you 20.
It's not good practice to store data in the DOM, if you're not actually using it for the purpose of layout. Yikes!
To better suit your needs, HTML5 provides a JavaScript API for handling client side storage. Depending on your circumstances, you have 2 options to choose from. The APIs are exactly the same, the only difference is the lifetime of the storage.
They are:
localStorage: Local storage is persistent; data stored in local storage is even available to the webpage after the user closes the browser completely and reopens it.
sessionStorage: As the name says, this data is only available for the current session.
Here's a link that will help you better understand these APIs so you can solve your particular problem: http://www.w3schools.com/html/html5_webstorage.asp

Can I access my requestScoped JavaBean-objects both client side and server side?

Short Version:
In a java web app, I can set javabean objects as requestscoped parameters, and access detailed fields, even hierarchical, within these objects through i.e. JSTL/EL while building a website.
Can I in any way access the full extent of these JavaBeans, in i.e. javascript-functions that are fired on, for instance, onclick of some elements within my web page?
Long version:
I am making a java web-app, and I am trying to learn the basics, so I am not using any frameworks like Spring or Struts, but I am building the app by the front controller pattern.
I have a page, which should be able to create new, recieve, edit and/or finally update data in my database. The database has foreign keys, and my choices in the editor should depend on the number of elements of other linked tables in the database.
I would like my editor to be able to:
Create the editor menu based on secondary tables of the database (static until leaving the site)
Load data from a database-element
Edit data in html-elements
Undo changes (which is basically repeating step 2, if data is available still)
Save data, and reset editor.
Point 4 is the center of attention here. I wish to be able to do step 4 without reloading the whole page. If I am able to do this, I figure step 2 should also be executed client side, as it does the same thing, only first time. It feels like a setup like this will grant me a good seperation of creating the form itself server side, and let step 2-4 happen client side, until step 5 again requires server side action.
I am not sure how to approach this goal though, or if it is a good idea. It is only a problem, when data is loaded from the database, and I want to store that data client side. Right now I am building the form in jsp/html/jstl, and I am using requestScoped java objects to do it, through a HttpServletRequest-object from the Servlet Controller. I have been trying to use these objects in javascript functions, with limited success. I have been able to extract all data, even hierirchal object's fields, except those in collections. Unfortunately these are essential to my editor page.
I have been looking into JSON for this, but is seems like i need to do big adjustements in my java code to implement this. Is it worth it?
finally, to repeat the question: How can I access requestScoped JavaBean-objectdata to be available client side, in i.e. Javascript?

Accessing a List object stored as a session variable in javascript

I have a list of id's stored in my ASP.NET application's session. For contextual purposes:
This is a facebook-like chat module. Id's are relevant to individual chat tabs.
jQuery is handling many things and requires the specific id of each box.
When a new chat session is created, it is given an id on the serverside used for client-side interaction like jQuery event binding
The program works fine I just need a way to access the list on the front-end. I would assume converting the object to a json object makes the most sense but I'm not quite sure where to start.
You can always render server-side content to the client by doing something like:
var ids = '<%= Session["Keys"].ToString() %>';
And then split the results and convert them however you want them. It really depends on what the ID's look like (just numbers, or is more info involved), and how you use them, so it's hard to provide additional advice without more information about the structures.
Add this to your project http://www.nuget.org/packages/Newtonsoft.Json then review this resource http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm to work out how to do the serialize/deserialize operations ;o)

Passing data between elements in UI

I'm new to web applications and am trying to understand the best way to work with data in HTML. I'm using Appengine (Python) and have managed to load a bunch of data to the view. In the simplest form, it's a set of movie names and each name has associated details with it (e.g. year, rating etc). Now how do I pass data between the movie link and then a div where all the details will be displayed? I'll be using jQuery for some controls in my application so I'm wondering if there's a way to do data binding to controls with that?
Additionally, can anyone tell me what're the standards around this i.e. if I load all this data to the UI in one call (assuming it's not a lot of movie titles), wouldn't it make it easy for people to screen scrape this information? Or is there some obfuscation that's typically used here?
Sorry if I'm not very clear but I really am an absolute beginner with web development!
Update1:
I found the jQuery data() api. It seems like this'll work. Comments?
Update2:
Some testing later and it turns out that data() actually attaches the data to the elements rather than showing it in a div itself.
There's a few ways to do it but the basic idea is to put the data in the HTML in a way that is not visibly rendered, then use Javascript to parse the HTML and pull the data out when you need it.
The easiest way on modern browsers is to use data- attributes. These are any attribute that start with data-, and you can name the rest yourself. For example:
Czar Wars
In this case, the user will only see a link called "Tsar Wars" but your javascript can easily access the data- attributes to get the data it needs. The other benefit of this approach is that jQuery will automatically make data- attributes accessible by the data() api.
Another way to do it is to have a hidden HTML list element with all your data elements in the list, but you'll have to parse this all yourself.
There's no standard obfuscation. You'll need to obfuscate yourself on the server side, and unobfuscate in your JS. It's not too difficult to figure out any obfuscation algorighm in js, so this is not worth your while.
If the data really is private, then you would have to architect it as to do all the processing on the server. For example, only show tokens (like 1234), and use AJAX calls to pass the token to the server so the server can do the data processing and spit back publicly safe results to the script.

Categories