client-side data storage and retrieval with html and javascript - javascript

I'm building what I am hoping to be a fairly simple, quick and dirty demo app.
So far, I've managed to build a bunch of components using only html and javascript. I know that eventually I'll hook-up a db, but at this point I'm just trying to show off some functionality.
In the page, a user can select a bunch of other users (like friends). Then they go to a separate html page and there is some sorting info based on the selected users.
So my first attempt was to put the selected users object into a cookie, and retrieve the cookie on the second page. Unfortunately, if the user changed their selection, the cookie wasn't getting updated, and my searches on StackOverflow seemed to say that deleting and updating cookies is unreliable.
I tried
function updateCookie(updatedUserList){
jQuery.cookie('userList',null);
jQuery.cookie('userList',updatedUserList);
}
but though it set the cookie to null, it wouldn't update it on the second value.
So I decided to put the selected users object into a form. Unfortunately, it looks like I can't retrieve the contents from the form on the client-side, only on the server-side.
Is there another way to do this? I've worked in PHP and Rails, but I'm trying to do this quickly and simply before building it out into something larger and am trying to avoid any server-side processing for now, which I have managed to do up to this point.

Since this is a demo, can you use HTML5? If so, you can use local storage: link text.
Another option is to use AJAX to load the other HTML page (replace whole body of the current document). Your storage variables would be stored in the <head>. This is a tightly coupled design, but again you're making a quick and dirty demo.

Is updatedUserList a string? If it's an array you might have to stringify it first:
jQuery.cookie('userList', JSON.stringify(updatedUserList))
(and of course parse it when you're retrieving it.)

Related

Find the last visited URL in javascript with history

I know about document.referer and this is not what I'm looking for.
It could probably be a solution but I want to retrieve it in local without using server.
Steps :
I'm pushing a new state in the current url of my page with history.pushState('','','#test')
I'm going to the next page.
And now I want to retrieve the URL but history.previous has been erased since Gecko 26.
Is there an other way of getting this value except from using cookies or sessionStorage?
One way of doing it would be to put the value in a parameter of the next page address, like so:
http://server.com/next-page-address/whatever.html?prevData=RequiredStateData
Note that using this approach, you might be exposed to users changing RequiredStateData in a malicious way. You can protect yourself using encryption or some checksum field.
So my problem was that there is no option for that purpose in local without a server environment.
If you find this question it's that you're probably in the same problem as me so the only option I found was to use.
sessionStorage.setItem('foo',val) and retrieve it with sessionStorage.getItem('foo').

Update html 'permanenlty' with no database?

I made a website for crowd-funding. I know that we should have used a platform for this. (other issues determined us not to)
The page that I have created has no database behind.
What I am trying to do is create some kind of hidden form that updates the sum that was raised so far.
I am not a very technical person but I do know that modifications made through javascript / jQuery ar usually temporary.
But, since scripts like website visit counters do exist I am wondering and appealing to the collective wisdom of this community:
Is there a way to update an attribute of a html element through some kind of hidden form without a database behind?
Perhaps writing to a .json file and updating the attribute from the data?
(I need to do this today as I will not be at the office during the campaign and it is very hard for a person that has no technical skills to do it... not that hard, but still, not user friendly.)
In order to display variable data, you need to get these data somewhere.
Do you have write access to your server file system?
What service level do you expect during data manipulation? Does it suffice if you just go and upload modified file every time manually?
What about embed in your Web page an IMG and then upload it with always the same name and different content?
There is a database even behind "dummy" hit counters, no magic.

"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

Dynamically / iteratively build up page content

I am planning to create a website which will let you iteratively construct an SQL query.
The idea is the following:
while(user wants more where clauses)
{
show selection (html select) for table columns
let user choose one column
upon selection, show distinct values of that column
let user choose one/multiple value(s)
}
I know how to handle the SQL part, but I am not sure how to tackle the iterative building of the page.
So my questions are:
What is the best method to build the page iteratively with the idea sketched above?
What do I do, if the user changes one of the previous selections?
The website will be build with Perl and I am thinking of utilizing Ajax for the dynamic part.
Any help is much appreciated.
If I were to do this, I'd use SQL::Abstract.
UPDATE:
If you don't want to redraw the whole page, you're going to be using AJAX. So find yourself a JavaScript library that you feel comfortable with that includes ajax calls. Jquery has this, a bunch of others do too. People have differing opinions on various libraries.
Anyway, your workflow looks like this:
user submits form
javascript performs client-side validation
javascript submits AJAX-style to the server
Server performs server-side validation, data manipulation, etc.
Server responds with data paylod
client updated the screen based on the contents of the payload.
So let's concentrate on 5 and 6.
Data Payload: The X in AJAX means XML, but many apps send back JSON, or HTML.
Update the Screen:
You can apply HTML directly to the existing page by setting a tag's innerHTML or outerHTML attribute. But that doesn't update the DOM. If you don't dig around the DOM in your clcinet code, then this can suffice. If you dig around, then you need to build nodes and add them to you page's DOM, so you might want to consider sending back JSON or XML.
So let's say that you have a div with id='generatedSQL' when your AJAX call retruns, it will fire a callback method (let's call it updateSQL()) and inside the callback you'll have code that looks approximately like:
$(#generatedSQL).innerHTML = theVariableHoldingTheHtml;
Your other option is to parse the JSONXML/etc. and using createNode(),etc, build new DOM bits and plug them into your page. I don't have the jquery chops to write this for you. I look it up every time I need to do something like it.
If the query text is only ever display-only, and you never try to dig around in it on the client side, just use the innerHTML method, whether you pass HTML or pass JSON and generate HTML from it. If the query text is important to the inner workings of the client, then you'll need to write bunch of DOM manipulation code.
No sure what you would be using but, if uses clicks on something then use the Onload event of the element with ajax call to script which brings back the data/content and on readystate just update the innerHTML of the container DIV.
Hope following link will help you understand the concept will give you a code to start with as well.
http://www.w3schools.com/php/php_ajax_database.asp

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