Two-way data-binding on XML in Javascript - javascript

I've just started working with Aurelia, so I would appreciate a little help regarding databinding.
I have a site that lets user create and edit a set of elements on the page. When a save is triggered, this page will translate the elements into an XML string and sent to the server. But what I would really like is to have a data-binding between the view and the XML, or at least the viewmodel and the XML, so I can inspect the resulting XML instantly on any changes I make to the elements. Do I have to parse an XML string back and forth for every change I make to the elements? How can Aurelia know to change the view if I change the XML? Is it easier to data-binding it with Json instead of XML, and then just translate json to XML upon change to monitor the result?

Sometimes the correct answer is "don't do it"
You are asking to bring a lot of pain on yourself.
I have no doubt that it is possible to write generic engine to have a synced version of XML<->JSON
But as long as it is your code, you will have to maintain it for the life of your app.
I bet you don't share the data between apps without backend.
Server side frameworks and languages are far more capable of transforming data between formats. You also would not have to implement real time synchronization on the fly.
For example asp.net mvc core or otherwise can accept request data in json and in xml and also send it out in those formats. You don't even have to care what app posts what.
You can have a logic added to any server side technology stack to parse data based on content-type.

Related

Building HTML client-side VS serving HTML server-side?

I always find it difficult to decide if I should render my HTML server-side or build it client-side.
Let's say I want to render a dynamic HTML dropdown with following requirements:
Shows records from a database table at page load
Must stay up-to-date (users can add/remove records from the database table using the website)
I can't decide between
Option 1
Render template with empty dropdown server-side
Populate dropdown client-side using ajax requests (JSON)
Update dropdown client-side using ajax requests (JSON)
Concern: Rendering empty elements before populating feels ugly to me
Option 2
Render populated dropdown server-side
Update dropdown client-side using ajax requests (JSON)
Concern: Why would you render server-side if you are still updating it client-side?
What solution is more commonly used in web development? Feel free to share different approaches.
This is a little opinion bases. There are schools for the server-side, and other schools for the client-side. The main reason for the later is utilizing the client machine (which are free for you) to free the server resources (which you pay for). This also makes your app more scalable.
The example that you gave is not detailed enough, and it is only one aspect. I usually use these general rules:
If there are dynamic parts of your page (e.g. dropdown, grid, popup form, etc), I use Ajax to avoid reloading the entire page.
If the HTML is very simple and/or requires further processing on the client-side, then just send JSON data from the server and build the HTML on the client-side. For example, I usually do not send error message from the server. Instead, I only send status codes (e.g. Successful, AccessDenied, Error, etc...) and I inspect those codes on the client and display the associated message. This is specially useful when different messages are displayed in different colors and styles or contain other HTML tags like links.
If it is a complex popup form or grid of data, then I send the HTML from the server. It is usually much easier and more flexible to build complex HTML on the server. Also when there are sensitive information used to build the HTML, it is usually much easier to build it on the server, otherwise you'll have to send some flags from the server or, better, you need to split your HTML building process to sections depending on permissions.
As for that very specific example in your question, I would go with the first approach (all client-side), mainly for the DRY concept (Don't Repeat Yourself). You don't want to have two pieces of code doing the exact same thing, and have to remember to update both every time you need change something.
Note though, that you don't have to send empty drop-down if you don't like it. Instead of only updating options like your example is suggesting, you can actually rebuild the entire dropdown every time. I don't particularly like this approach, especially if there are event listeners and other references attached to the dropdown, but I just wanted to say other ways to do it. This method can be useful on some scenarios, especially if the dropdown is part of a bigger section of the page that this whole section requires updating (rebuilding) every time, in which case I usually opt for sending the HTML from the server.
Your concerns are valid, each case has its advantages and disadvantages as you mentioned.
I would, personally, go with the first approach (all client-side); mainly for code maintainability. With this approach, you only have to update the HTML client-side instead of both client-side and server-side.
However, there is an argument to be made for saving that one request by server-side rendering the values. Even though it might be insignificant, there is a small performance optimization.
That depends. are you worrying about SEO?
Are you using any kind of client-side framework? I will assume that you don't, since JavaScript frameworks have there own way to do this, if you want you can read more about angular/react/vuejs which is the hottest JavaScript frameworks those days that will solve this issue.
Client-side frameworks render HTML on client-side only, and use only Ajax API to receive data from the server.
But if you don't want to use any client-side framework and do it in the "classic" way, both ways are appreciated. I tend to like the first way, this is almost how client-side frameworks do it and makes the most sense, yes you render empty table but you only render the "container" of your data, if you're bothered by how it looks visually (Showing empty list before data is fetched) you can just show loading bar or hide the table till the data is fetched.

MVC: Pass HTML template in JSON response rather than separate resource?

I'm planning to write a web app using either Backbone or Angular. We want to push "widgets" from the server to the client (i.e. semi-complicated, dynamic but largely autonomous UI elements... something maybe like the popular TodoMVC app). So we'll need to send over a template, some javascript (controllers etc.), probably CSS, and JSON data (models).
We're debating how to send over all the information. How much can be, and what should be encapsulated in the JSON?
Is it possible to create files out of data passed over? i.e. could we pull out CSS and apply the rules to our document? I believe it would be easier to run javascript passed over this way.
I'm under the impression that being able to cache the template is important... does that require loading it as a (separate) resource rather than as part of some huge JSON object?
As for CSS, it needs to be loaded before inserting into the DOM (so we don't want just a promise). Would it make sense - or even be possible - to pass our CSS rules in the JSON and extract them somehow?
EDIT: to more fully describe what I'm working with, I'm focusing only on the front-end. The back-end can be customized to send over resources however we want - they'll optimize that depending on what the front-end needs. Our backend stack includes MongoDB, Tapestry, ActiveMQ.
The payload that needs to get sent over will be all the resources necessary to push something like a Mac Dashboard Widget or Windows Gadget into the browser. So HTML, CSS, Javascript, data will all get sent over. We want things to be snappy and minimize server requests as much as possible, as some of these payloads may get to be somewhat large.
Your questions are rather vague and the answers can change by coding on a different build platform. Your chosen application design can also impact the best practices to follow for implementing X type of application to X device(s). There's more than one way to skin a cat ya know.
What information are you sending over? Is it a lot of raw data arrays? Is it more document based where XML could be more beneficial? You'll need to work with your DBA if the data is stored in a repository and you'll be querying it. Will you need to write code to format your data or will the DBMS output it in the format you need?
What do you mean the CSS needs to be loaded before being inserted? Everything loads in the order you specify so making sure your CSS loads at the proper time shouldn't be an issue. If you're using ASP.NET, you can also use a SSM (style-sheet manager) to serve your CSS and only load whats required. SSM's are great if you have a lot of style-sheets to serve.
A lot of the questions you asked will be answered as you get further into the design phase. In order to get some solid answers and not just speculation on what is the best method, you will need to publish a lot more details than this. Any answers at this point shouldn't carry much weight in your decisions. They certainly wouldn't mine.

Should I send raw data or Html as an Ajax response?

I have a site written in Asp.net webforms. It uses ajax heavily.
Most forms on the site are submited with javascript. Javascript validates the input and sends it to /ajax.ashx on the server. The server processes the request and sends back a JSON response. My javascript uses the JSON to create html, which it inserts into the Dom.
I'm making a new version of my website written using asp.net MVC3. I've been looking at tutorials on this subject, and some of them recommend doing ajax in a different way. Rather than sending data and then building + inserting html with javascript, they create html at the server, and use javascript only to insert it into the Dom. For instance, in this tutorial.
Which way should I use? Using the new method will be quicker, but is it better?
That's a subjective question. Both approaches are possible and there is no better way. There are pros and cons of each approach.
Building the HTML on the server is easier and will require you less efforts but consumes more bandwidth compared to the first approach.
If you decide to go the first way you could use some client side templating framework which might help you simplify the generation of DOM elements on the client.
Creating html code directly into the server and injecting it with an ajax call is very fast and simple, the real problem is that in that way your service is bound to be used with that specific application. By sending RAW data you allow any app to use that data in any way, without bounding it to a specific application.
returning json feels more flexible to me; you can change what happens with your json response, like the layout it results in. If you return html you return data mixed with layout. This doesn't feel right to me.
I believe it is better to separate the layout from the actual data. That is why you should pass data between your scripts and not HTML.
If you go about it sending HTML, consider that you would have to build valid HTML and CSS, which might not sound hard at first but then you'll start using CSS that is not loaded in the file calling the ajax, etc.
Always separate content (data) from layout. That's why there is HTML and CSS, to separate layout from data. So why mess things up by mingling HTML between data?
Building the html serverside will probably be faster and not bog down the client which is important. Rendering data into HTML with javascript takes time and not every browser is fast with js (i.e. older versions of IE) so things can slow down if you're doing a lot of this.
Like previous posters said, it's kinda subjective because it depends on how much you're offloading to the client. I'm of the opinion that if you can do things serverside, you should.
If you are going to be using this service to return JSON to other applications/clients, then it's probably a good idea to just leave it as JSON and let the client do what it needs on their side.

Render partial view on the server or send json data and render template on the client

I was wondering what would be a good approach (or recommended approach) to render partial views in a web application.
I have a requirement where I need to load data into an already rendered page using AJAX, sort of like a "Load more..." link at the end of the page which grabs more information from the server and renders it to the bottom of the page.
The two options I am playing with at the moment for the AJAX response are
Return a JSON representation of the data, and use a client side template library, (e.g. jQuery templates) or just plain javascript to turn the JSON into HTML and append to the bottom of the page
Render the partial view on the server (in my case using grails' render template:'tmplt_name') and send it across the wire and just append the result to the bottom of the page
Are there other ways to do this? If not, given the above options which would be better in terms of maintenance, performance and testability? One thing I am certain about is that the JSON route will (in most cases) use up less bandwidth than sending html across the wire.
This is actually a really interesting question, because it exposes some interesting design decisions.
I prefer rendering partial templates because it gives my applications the ability to change with time. If I need to change from a <table> to a <div> with a chart, it's easy to encapsulate that in a template. With that in mind, I view almost every page as a aggregate of many small templates, which could change. Grails 2.0 default scaffolding has moved towards this type of approach, and it's a good idea.
The question as to whether they should be client-side templates or server-side is the crux of the issue.
Server side templates keep your markup cleaner on initial page load. Even if you use something like Mustache of ICanHazJS, you kinda sorta need to have an empty element in the page (something with your template), style it appropriately, and work with it in Javascript in order to get update your info.
Drawbacks
"chatty" applications
larger envelopes across the wire (responses include HTML, which may be considered static)
slower UI response time
Benefits
Good for people with lots of server side language experience
Maybe easier to manipulate or modify in a server-side environment (e.g. return a page embedded with multiple templates, which are programmatically loaded and included)
Keeps most of the application stuff "in one place"
Client-side templates can really reduce server-load, however. They make an application "less -chatty", in that potentially you could minimize the number of calls back to the server by sending larger collections of JSON back (in the same number of bytes, or fewer, that would be taken up by HTML in a server-side template scheme). They also make UI experience really fast for users, as clicking an "update" link doesn't have to do an AJAX round trip. Some have said:
Anthony Eden #aeden 10 Dec Reply Retweeted Favorite ยท Open
the future of web apps: requests are handled by functions, logic is always asynchronous, and HTML is never generated on the server.
Drawbacks
Not great for SEO (un-semantic extraneous UI elements on initial page load)
Requires some Javascript foo (to manipulate elements)
Benefits
- Responsive
- Smaller envelopes
Trends seem to be moving towards client side templates, especially with the power exposed by HTML5 additions (like <canvas>)...but if leveraging them requires you to rely on technologies you're not extremely familiar with, and you feel more comfortable with Grails partials, it may be worthwhile to start with those and investigate refactoring towards client side templates based on performance and other concerns later.
in my view the second option rendering partial is better because if you get a json data you are supposed to manipulate it like set style, create elements, set values and similar thing as per the need just after you get ajax response in javascript but if you render partial, you can design your view in that partial before and keep ready and just import using ajax call so there is no responsibility of handling the response data.
I would say it depends on how much data you're sending across the wire as you put it. If you're implementing a "load more" feature then it seems like you wouldn't want to take 5 seconds to load something. Google images is a good example of how quick that feature should be. If you know you'll never have that much data then rendering the partial on the server might be cleaner, but if you're requirements change then it's a hassle to go back to the first approach. So in short, I'd say the first approach allows for more disaster control as far as how long a load more takes to load a large amount of data. I'd say it's also general good practice to take load off server when you can, even if it's a little inconvenient on the client side for the developer.

Communication between Javascript and the server

I've been developing a "Form Builder" in Javascript, and coming up to the part where I'll be sending the spec for the form back to the server to be stored. The builder maintains an internal data structure that represents the fields, label, options (for select/checkbox/radio), mandatory status, and the general sorting order of the fields.
When I want to send this structure back to the server, which format should I communicate it with?
Also, when restoring a server-saved form back into my Javascript builder, should I load in the data in the same format it sent it with, or should I rebuild the fields using the builder's createField() functions?
When making and processing requests with JavaScript, I live and breath JSON. It's easy to build on the client side and there are tons of parsers for the server side, so both ends get to use their native tongue as much as possible.
This seems like a perfect scenario for using JSON as a serialization format for the server. If you study a few examples it is not too difficult to understand.
Best practice on this dictates that if you are not planning to use the stored data for anything other than recreating the form then the best method is to send it back in some sort of native format (As mentioned above) With this then you can just load the data back in and requires the least processing of any method.
I'd implement some sort of custom text serialization and transmit plain text. As you say, you can rebuild the information doing the reversed process.
There's a lot of people who will push JSON. It's a lot lighter weight than XML. Personally, I find XML to be a little more standard though. You'll have trouble finding a server side technology that doesn't support XML. And JavaScript supports it just fine also.
You could also go a completely different route. Since you'll only be sending information back when the form design is complete, you could do it with a form submit, for a bunch of hidden fields. Create your hidden fields using JavaScript and set the values as needed.
This would probably be the best solution if didn't want to deal with JSON/XML at all.

Categories

Resources