I have a project on asp.net mvc.
In some situations, when user do something, a part of html page should be updated. Whole page shouldn't be reloaded. For example, user clicks on the product category and a html markup with new products should be loaded.
What is the best practice - to use partial view and Ajax.ActionLink to update partial view products, or use $.ajax for receiving info about products and then generate html markup in javascript?
Or maybe the best practice is something else?
It depends on what your requirements are. In general, as you say, there are two methods:
Either load the formatted HTML through Ajax, or load a JSON and then create the HTML yourself. Each has its advantages and disadvantages:
Loading HTML
Advantages:
You can do generation on the server-side, thereby keeping the client-side code clean
Disadvantages
The size of the packet you send over the wire will be bigger
The request is very specific to that method alone, and it will be difficult to reuse
Loading JSON
Advantages:
Payload is as small as can be
Since you're not tying it to one implementation, you can reuse the JSON for other purposes (a mobile client for example)
Disadvantages:
Generation of HTML has to be done on the client-side. If you're doing this manually or with jQuery, this can be cumbersome and tends to grow the client-side script. (a solution would be to use a templating engine such as moustache.js or handlebars.js)
Your rendering logic is on the server AND on the client, which means not everything is in one place
As you can see, both have there pros and cons. There's no real hard rule here, and it depends on your situation.
In general, my advice would be if you want something quick and you don't think you will need the same method elsewhere use dynamic HTML loading. If you think you might want to reuse the data on other pages or with other clients, use JSON with a templating engine.
Related
Ok so im learning javascript and I just wanted to know if its possible to make it do actions on external pages. For example if I wanted to say 'onload redirect to somesite.com/page1 then once on somesite.com/page1 fill in register form with these details'
is that possible?
You cannot do this.
This would represent, for lack of a better word, an enormous security hole.
The only way to make an external page "do stuff" is to write code that is on or explicitly included in that page itself. Period.
I have however, seen external pages get loaded INTO the current page as strings, and then have the javascript that loaded those pages modify that markup directly. But that is ugly.
On the first page you could modify some variables/values in a database. Then, in the second page you could check the values in your database, and do different "stuff" depending on those values.
You would need to set up a database and use some server-side scripting along with Javascript (server-side scripting is used to interact with your server/database). In your first page, the server-side script, like PHP, would fetch info from your Javascript. In your second page, your Javascript would fetch info from your server side script and then do stuff to that page.
This is a much safer way. If you are taking user input from things like HTML fields, you need to look into cleaning the input to prevent something called "cross-site scripting (XSS)".
You could do this IF you were rendering the other page in a frame of some sort.
There are multiple ways in which you can render an entire external page as a piece of your page. Many pages take precautions to block being rendered in a frame for just this very reason though (Not to mention copyright issues).
Once you're rendering the external page inside your page you should be able to reference components nested in your frame and do the sort of thing that you're describing.
There's no way to do this with JavaScript. The developers of all the major browsers work very, very hard to prevent this sort of thing. If this were possible, it would open up pretty massive security holes.
If you really want to use something like this for testing, you can look at browser automation software like Selenium. This allows you to automate various testing scenarios in your browser, but it does not affect other clients using your site.
I'm working on a project which needs to load via AJAX some HTML information on the page.But I'm not quite sure how to load that information.
I don't know which method is better for me:
1) Load the entire HTML with AJAX and then just append it to the page
or
2) Load only the data with AJAX and then build the HTML using Javascript(+JQuery)
The one I tend to use is the first method because it's the easiest one but also it is more expensive regarding the memory (the biggest file I have to load has about 7kb which is not too much)
The second one which is the hardest, involves a huge Javascript (Jquery) code to build the HTML(I have also to load the attributes for the element).And because I have lots of different HTML code to load I have to make lots of conditions (e.g. one for a button, one for a title, one for a textarea etc) and also I have to create variables that containes that HTML.
My question is what method is the best to use in my case?
I would always stick to the solution where I cleanly divide data/logic and view. This would probably the case in the first alternative. Making changes to HTML generated with JavaScript is quite hard.
I'd suggest another option: Use client side templates. Load the template and the data with an ajax call and then fill out the template using javascript. There are some libraries out there for this scenario.
I can imagine a couple of developers working: A full-time back-end developer and a full-time front-end developer.
The BE developer has to send some data for the FE developer to display it right. Thinking of programming as easy as possible, he chooses the first method described by the OP. Everyone is happy.
A few months later, the presentation of this very data needs to be updated. The manager quickly calls the Front-End developer, which says:
"Uhhh... No can do. The entire data already comes formatted directly from the server."
Oh noes! Would this have happened if the data came only as RAW DATA from the server? I wonder =)
the second method:
Load only the data with AJAX and then build the HTML using Javascript(+JQuery)
is much appropriate, one main advantages of these method is your ajax response will become faster.
Also, it is more logical to separate the logic from design.
Note: always the best solution is depend on your specific case.
This is a design question. I find myself going back and forth between two UI design styles.
The UI on a prototype I developed recently relied heavily on loading the elements of the UI as partial views via AJAX. I did not like that approach because I had to do a lot of requests to the server while my page was loading. However, the plus of this design was that I could easily edit the partial view templates, so the code was easier to manage.
In the next iteration I decided to package all the information at once and then use JavaScript to generate partial views and plug this information into it (and only use Ajax when on-demand up-to-date information was actually needed). My page loads faster, but I find myself generating a lot of HTML snippets in JavaScript, which is getting harder to manage.
As I see it, using Ajax you get:
Easier to maintain (+)
Longer UI response times (-)
And with JavaScript only, you get
Faster UI response (+)
Easier to handle server-side errors (+)
Harder to maintain (-)
So, There are a few things on which I would like to hear your comments:
I do not like using Ajax unless I don't have a need for actual on-demand data. Am I wrong?
Are there frameworks/libraries that would make managing HTML-generating JavaScript code easier?
Are there any other pros/cons of the two approaches that I have missed?
Thanks,
There are templating libraries for JavaScript, if you want to get that involved. In general I would avoid manually sticking together HTML strings from JS unless there's a particular need to (eg in some cases for performance when dealing with very large tables).
HTML-hacking is difficult to read and prone to HTML-injection security holes when you don't get escaping right.
Start instead with the DOM methods, and use DOM-like content manipulation libraries to make it easier. For example, if using jQuery, do this:
$('<a>', {href: somelink, text: sometext})
and not this:
$(''+sometext+'') // insecure mess
There doesn't need to be a big difference between fetching data through XMLHttpRequest vs including it in the HTML document itself. You can direct a bunch of JSON data to the same function that will build page parts whether it was just fetched by XMLHttpRequest in an update operation, or included in function calls at document load time.
When including data in the page you will generally need to include a timestamp they were generated in any case, so that if the browser goes back to the page a while later without reloading it, the browser can detect that the information is now out-of-date, and cue up an XMLHttpRequest to update it.
The usual question when you're creating your page content from data with client-side JavaScript is, are you going to fill in the initial static HTML version from the server too? If so, you're going to be duplicating a lot of your content generation work in both client-side JS and the server-side language(*). If not, then you're making the content invisible to non-JS user agents which includes search engines. Whether or not that matters to you typically depends on what the app is doing (ie does it need to be searchable and accessible?)
(*: unless you can use server-side JavaScript from something like node.js and re-use your content generation code. This is still a somewhat rare approach.)
Why not look at integrating require.js into your workflow? I'm not entirely sure how it would work with templates, but included in their pipeline is the ability to package all required script files into a single .js to be served by a single server request/response.
I have no personal experience about it, but Closure looks promising. The thing about its templates being usable on both server and client side might be of interest to you. Here is what was said about using it in Google+:
The cool thing about Closure templates is they can be compiled into both Java and JavaScript. So we use Java server-side to turn the templates into HTML, but we can also do the same in JavaScript client-side for dynamic rendering. For instance, if you type in a profile page URL directly, we'll render it server-side, but if you go to the stream say and navigate to someone's profile page, we do it with AJAX and render it client-side using the same exact template.
When working with remote data after a page is loaded, for small datasets I prefer returning data only and adding to the UI with templates.
For large datasets, I recommend using your partial views to render the html on the server to reduce overhead in the client as #bobince mentioned.
For client-side state tracking, check out Knockout at http://www.knockoutjs.com. It uses an MVVM approach with data models bound to UI elements and makes it very simple to send the data back to the server via AJAX. It works with the jquery.tmpl template library out of the box or you can integrate another library of preference with a little more effort.
As far as managing templates, it's easy enough to store common templates in an object, either on the server to be retrieved with your remote data, or in a javascript object on the client.
I'm working on a project and there is some battle between how some JS filtering should be implemented and I would like to ask you guys some input on this.
Today we have this site that displays a long list of repeated entries of data and some JS filtering would be nice for the users to navigate through. The usual stuff: keyword, order, date, price, etc. The question is not the use of JS, which is obvious, but the origin of the data. One person defends that the HTML itself should be used and that the JS should parse through it making the user's desired filtering. Another person defends that we should use a JSON generated in the server, and that JSON should be the data's origin.
What you guys think on this? What are the pros and cons?
As a final request, I would like you to be the most informative as possible since your answers will be used and referenced for all us in the company. (Yes, that is how we trust you!:)
The right action is matter of taste and system architecture as well as utility.
I would go with dynamically generated pages with JS and JSON -- These days I think you can safely assume that most browsers has Javascript enabled -- however you may need to make provisions for crawler (GoogleBot, Bing, Ask etc) as they may not fully execute all JS and hence may not index the page if you do figure out some kind of exception for supporting those.
Using JS+JSON also means that you make your code work so that support for mobile diveces is done client side, without the webserver having to create anything special.
Doing DOM manipulation as the alternative would not be my best friend, as the logic of the page control and layout is split-up in two places -- partly in the View controller on the webserver, and partly in the JavaScript -- it is in my opinion better to have it in one place and have the view controller only generate JSON and server the root pages etc.
However this is a matter of taste, and im not sure that I would be able to say that there is one correct and best solution.
I think it's a lot cleaner if the data is delivered in JSON and then the presentation HTML or view of that data is generated from that JSON with javascript.
This fits the more classic style of keeping core data structures separate from views. In this manner you can generate all types of views without having to constantly munge/revise the way you store, access and manipulate the data. You can even build classes and methods to develop a clean interface on your data that is entirely independent of how that data is displayed.
The only issue I see with that is if the browser doesn't support javascript and that browser is a desired viewer. In that case, you have to include a default HTML version from the server that will obviously not be manipulated and the JSON will be ignored.
The middle ground is that you include both JSON and the "default", initial HTML view of that data in rendered HTML. The view comes up quickly and non-JS browsers can see something useful. But, then any future manipulation of the view (sorting, for example) uses the JSON data and generates a new clean view from the JSON data. No data is then ever "parsed" from the HTML view.
In larger projects, this also can facilitate the separation of presentation from data manipulation so different people may work on creating HTML views vs. manipulate the data (like sorting).
I would make the multiple ajax calls to the server and have it return the sorted/filtered data. If you server backend is fast than it won't be very taxing and you could even cache the data between requests.
If you only have 50-100 items than it would be reasonable to send it all to the client and have javascript sort and filter it.
Some considerations to help make the decision
Is the information sensitive and unique? (this voids and benefit to caching in my first point)
What is the most common request that will happen and are you optimizing for that?
How much data is there? (tens of rows, hundreds, thousands, millions)?
Does you site have to work with JavaScript turned off? (supporting older browsers?)
Is your development team more comfortable doing this in the front-end or back-end?
The answer is that it depends on your situation.
Hey everyone, I've been thinking about how the majority of web apps works at the moment. If as an example the backend is written in java/php/python what you probably see is that the backend is "echoing / printing" the html ready to the browser, right.
For web apps that works using almost exclusively ajax, is there a reason to not simply communicate without html, as an example just by using JSON objects passing back and fourth between the server and client, and instead of "printing or echoing" html in our script/app backend we simply echo the json string, ajax fetches it and converts the JSON string to an object with all of our attributes/arrays and so on.
Surely this way we have less characters to send, no html tags and so on, and on the client side we simply use frameworks such as jQuery etc and create/format our html there instead of printing and echoing the html in the server scripts?
Perhaps people already do this but I have not really seen a lot of apps work this way?
The reason is that I want todo this is because I would like to separate the layer of presentation and logic more than it currently is, so instead of "echoing" html in my java/php I just "echo" json objects, and javascript takes care of the whole presentation layer, is there something fundamentally wrong with this, what are your opinions?
Thanks again Stackoverflow.
There are quite a few apps that work this way (simply communicating via AJAX using JSON objects rather than sending markup).
I've worked on a few and it has its advantages.
In some cases though (like when working with large result sets) it makes more sense to render the markup on the server side and send it to the browser. That way, you're not relying on JavaScript/DOM Manipulation to create a large document (which, depending on the browser, would perform poorly).
This is a very sensible approach, and is actually used in some of our applications in production.
The main weakness of the approach is that it increases the load on the browser resource-wise and therefore might - in light of browsers often already-sluggish JS performance - lead to worse user experience unless the presentation layer mechanics is very well tuned.
Now a days many webapps use this approach like gmail and other big apps even facebook this
the main advantage of this approach is user dont need to refresh all the pages and he gets what we want to show him or what he desired.
but we have to make a both version like ajax and normal page refresh what if the user refresh the page.
we can use jquery template which generates html and also google's closer which is used by a gmail and other google products.