Uses of serialization in a web application - javascript

I'm teaching JS my self and I just been reading about objects JavaScript Objects in Detail which also discuss object serialization. So I tired to read more about that in order to understand the concept and to find a real use. So I found many tutorials on how to use JSON.stringify() and JSON.parse(), but I still can't come up with a scenario when I would need to serialize an objecct. The only one scenario I've used so far was to serialize a from with jQuery in order to sent data with .post(), but I'm not to sure if this is related.
What are the most common scenarios for serializing an object in a web application?

There are lot of scenarios, the most useful I can think of is when you want to store the data offline ( for example mobile or desktop application), you can use localStorage to store the serialized data (using JSON.stringify()) and load it back by parsing it into object (using JSON.parse()).
This offline storing of data is useful when the user don't have internet access and the user still wants to see already fetched items.
Note:
You can find more info at below references:
localStorage Reference
How to use local storage

Related

can I use indexDB to store sipml5 client objects

regarding this problem:
Call get disconnected while I am refreshing the SIPML5 demo page .
can be found here
https://groups.google.com/forum/#!msg/doubango/BlAww-8Wq4U/79Rupoa4BwAJ;context-place=searchin/doubango/page$20refresh%7Csort:date
I am searching for a solution to keep the call going even if the client page get refreshed
I know that all variables lives inside the javascript file will be re-created when a page get refreshed but my question is :
can I use indexDB to store all the objects that sipml5 client use so the call never get disconnected on page refresh?
Yes, you can store and retrieve sipml5 client objects from and to IndexedDB since it can store any type of objects and use Structured Cloning Algorithm to serialize the data. Basically it can save all javascript data types in plain object, in nested or in circular reference.
The structured clone algorithm is an algorithm defined by the HTML5 specification for copying complex JavaScript objects. It is used internally when transferring data to and from Workers via postMessage() or when storing objects with IndexedDB. It builds up a clone by recursing through the input object while maintaining a map of previously visited references in order to avoid infinitely traversing cycles. You can get more information from here

Where I should keep data using AngularJS?

I've got a question about storing data in AngularJS. Should I use some kind of service, or controller to keep data? I saw different codes in Angular and one time people store data in service, other, in controller. I would say that the proper way is to keep it inside factory, but is it a good practice?
Thanks!
Well, it depends on what you mean "storing data" for you...
If you mean keeping data in some place just for passing it between controllers, then this place is a service.
If you mean keeping data so it can persist even after a page refresh or after closing the browser and reopening the same app then you can use the javascript apis for sessionStorage and localStorage (take into account that older browsers may not have these apis and you would have to polyfill them). I've used an angular service for this that have given good results: https://github.com/tymondesigns/angular-locker.
If you mean persist the data for using it among other systems different than yours, the you should rely on a database server, either yours or from a third party (take a look at Firebird).
Of course you have more options, but they don't differ from the ones you have if you use plain javascript. Each of them could be treated in an "Angular way" if you create a service to manage them (IndexedDB, WebSQL, etc.) In the end it depends on what you're trying to achive.
If you need to use the data across multiple views / controllers, for example a logged in user, then i would recommend a service which holds the data for you. This way you can access it from anywhere you inject it. However, if you need your data only in one of your controllers, i dont see a reason to create a service, just store it in the controller.

How to pass javascript object from one page to other

I want to pass javascript object from one page to other page so anyone can tell me how to do it?
Is that possible to do so using jQuery?
Few ways
Server side postback
Have a POST form on your page and save your serialized object inside a hidden input then post it to the other page. You will be able to process that data on the server and most likely put it back somehow into the page. Either as javascript object or anything else.
Client side URL examination
Make a GET request to your other page by attaching your serialized object to URL as:
http://www.app.com/otherpage.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using Javascript.
What's in a window.name = local cross-page session
This is a special technique that's also used in a special javascript library that exposes window.name as a dictionary, so you can save many different objects into it and use it as local cross-page-session. It has some size limitations that may affect you, but check the linked page for that and test your browsers.
HTML5 local storage
HTML5 has the ability of local storage that you can use exactly for these purposes. But using it heavily depends on your browser requirements. Modern browsers support it though and data can be restored even after restarting browsers or computers...
Cookies
You can always use cookies but you may run into their limitations. These days cookies are not the best choice even though they have the ability to preserve data even longer than current window session.
Javascript object serialization
You will of course have to use some sort of a (de)serializer on your client side in some of the upper cases. Deserializers are rather easy to find (jQuery already includes a great function $.getJSON()) and are most likely part of your current javascript library already (not to even mention eval()).
But for object to JSON string serialization I'd recommend json2.js library that's also recommended by John Resig. This library uses in-browser implemented JSON (de)serialization features if they exist or uses it's own implementation when they don't. Hence recommendation.
That is only possible if the pages exist at the same time, and one page is opened from the other so that you have a reference to the other pages windows object.
If you navigate from one page to another, they don't exist at the same time, so you can't communicate like that. You would have to serialise the object into a string that you can send along in the request, for example sending JSON in the query string.
There are different ways of persisting data, like in the query string, post data, cookies, window name or HTML5 local storage, but all those methods can only persist string values, not Javascript objects.
This is possible to do, and you have a couple of options.
Local Storage
Can be added/eddited/removed at any stage and accessed across a domain. (doesn't work natively in ie6 and ie7 however there are work arounds for that)
The Window Object
I would put a massive cavet around this not being the best solution, it's not at all secure, so only use it for things that don't need to be kept private. window.name = { "json" : "object"} which is then available in the following page in the window.name property.
I believe that the only way to pass a javascript object from one page to another is to serialize it into string and pass it in url. For example if you have object
var temp = { id: 1, value: 'test' }
you may want to use JSON-js to serialize it and pass it in for example http://mysite.com/?data=serialization. Then after you load the page you need to deserialize it via for example $.parseJSON().
If your application uses sessions, you could serialize it (as per other answers) then POST it to the server where it is stored in a session variable. In the next page, you retrieve it from the session variable.
In Javascript, normally all variables only exist in a scope that is unique to that page load. They don't persist between different pages if there is a new page load.
The exceptions to this are
Cookies.
Local storage.
Cookies are truly cross-browser but are extremely limited in terms of size. You shouldn't expect to be able to store more than 4kB of cookies for a page reliably; in fact you probably shouldn't be using any more than 1kB. Cookie data slows down the loading of every page and other request, so it should be used sparingly.
There are various types of local storage available to Javascript, but the only practical cross-browser implementation of this is HTML5 webstorage which is implemented in all modern browsers (IE8+, FF, Chrome, Safari, etc), but is notably not implemented in IE6 or IE7, if that matters.
Both these approaches store a value in the user's browser which can be made to be persistent so that it can be written to and read from by pages from the same site, even between page views (and even, often, between browser sessions or computer reboots).
I wrote a library some time ago, that can store most js objects to localstorage. For example instances of your prototype classes, with references to other objects, self references included. Bare in mind that IE support is lackluster.

Is there a REST based ORM?

I've been looking at JavaScriptMVC, and I'm pretty interested in the idea. I'm wondering, though, if there are any ORM solutions for such an architecture. It seems like you will end up having to write two data access layers, one server side to fetch items from the database and one on the client side to retrieve items via AJAX.
My question is, are there any existing (preferably open source) solutions that would let me define a model (XML or class definition) and generate a REST api for me to access my data. I've been looking at DataMapper while I'm thinking about this, and it would be great if create a model, and instead of calling Person.all(:age.gt => 30) like I would in ruby I could just query /Person/All/?filter="age>30" (properly escaped of course) and get back an object serialized to XML without having to write the controller myself.
Is there anything out there like this? Does this seem like an intelligent way to go about framing a javascript based app?
After some more research, I think I've found my answer. Using CouchDB I can have all of the application logic running in the clients browser and use the built in REST api to persist the data to the server. This way, I could even manage the model in the client side javascript.

Generate JavaScript objects out of Django Models

I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions get(), save(), all() and count() available to the client. Additionally, it would be great to have the field list of the model already available in the generated JavaScript object.
Whether the current user can read or write the records is a separate issue I will deal with using Django's authentication. For the time being, retrieval would be a start.
In short, is there code that would generate a JavaScript model from a Django model?
Thanks.
It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the methods) but you'd need to expose a web service that can handle every kind of DB-API call. I can't even begin to imagine where to start and the security issues may be too numerous to easily overcome.
The alternative (and much simpler) approach would be to use one of the various Django REST modules and JSON serialization. You could perform an AJAX GET request on a resource, which can be identified by a series of query parameters that would be equivalent to chained queryset filters. This would return the JSON representation of the model's values. You can then modify the JavaScript object and use an overloaded AJAX POST request to persist the changes back to the server. You wouldn't have access to the model's methods, so that functionality would have to be reimplemented but making any changes to a model should be straightforward enough - This is basically the JavaScript equivalent of using an HTML form to modify data.
You need a data serializer. You can do it with django built in serializers. It is documented on official django site. djangoproject_topics-serialization
I've started a project that I think does exactly what you're looking for. You can find it at
github_bumby_jslib. It currently only supports get(), but I'm hoping to extend this soon. Feel free to contribute patches :)
jslib is a Django application aiming to simplify AJAX integration with your Django projects.
It sounds like you want to JSON encode your object data. See JSON.org for more on the data format.
So it's been a while since I posted the original question and since then there has been a number of developments in Djangoland. Not least of which is a great little library called Django REST Framework. I will be using it on a new project and it's looking pretty kewl.
http://www.django-rest-framework.org

Categories

Resources