What is your opinion (PRO an CONS) about returning HTML code as a result for an AJAX call. It is, if the app creates a new item in a list and it needs some extra parameters or some pattern customization, instead of modify it through JS, we can send it templatized through an AJAX call.
The point is that HTML snippets are sent from the server to the client computer and integrated in the document DOM. Any problem with this approach?
No problem with it at all, perfectly normal and reasonable thing to do.
There is sometimes a use-case for sending data rather than markup and expanding it with client-side templating, but that's mostly for situations where you're sending a lot of data and so want to keep the size on the wire down. (E.g., a large table where the HTML representation of it is 100k but the raw data in, say, JSON format would only be 10k.) Or when the templating varies depending on client-side conditions. But by and large, perfectly fine to send HTML you then incorporate into the DOM via innerHTML (or any of several libraries' wrappers for it that help you with the odd niggle).
This is a common approach.
If you're adding items to a list or replacing the contents of a pod with something completely different this is fine.
This also makes it easier to apply AJAX to existing sites (for example overlays or something) because you can make requests to existing pages and then strip out the bits you don't want.
However, it would be better for updates where only a value is changing then you should perhaps use Json there.
Personally, I almost always choose to receive a JSON response with no markup or formatting applied, but that's just because I like having a really flexible, granular response so I can do whatever I want with the returned data, without having to possibly strip it out of HTML. This is NOT necessarily the easiest or most elegant solution in a lot of cases! :)
Related
Let's say we have a group of HTML element like this JS fiddle with certain behaviors. Having one of this is easy on a HTML page.
But what is the best practice of having 1000 of them (the same JS fiddle) on a page? This is not only about dynamically generating required HTML elements but more importantly generating the behaviors/JS codes for each individual element (with different values and id).
An Example:
document.getElementById("ID1").onchange = function () {
//some complicated behaviors
};
Generate the a ID2/ID3/ID4...ID1000 version of the above codes in run time when needed. Note that it must be running on HTML environment with no servers. Select options/data are stored in the same html file (as an array or some sort).
Any advice or suggestions are appreciated.
Ideally, rather than loading up all the possible options in the DOM, you would use AJAX to fetch the next set of options from the server. So when you select the state, it goes and grabs the counties for that state, then when you select the county, it goes and grabs the cities for that state.
To go further, when you select the state, it sends the selected state back to the server to fetch all the counties for that state. Then when you select the county, it sends that back to the server so it can fetch the cities.
You can use the server side language of your choice of course (PHP, ASP.net, Ruby, Python, etc.)
Otherwise, you're injecting a ton of data in to your DOM that will never get used and that would vastly increase load times; whereas AJAX is generally pretty fast.
There are lots of tutorials regarding the use of AJAX so I'm not going to cover that in the answer, but that is your best solution.
You tagged the questions only with Javascript so I assume that you have the data locally and you don't retrieve it from a server.If you take the data from the server use Ajax and get only the data that you need at that moment.
With Javascript you can use
document.createElement('element'); // this is faster than Jquery if you generate a lot of data
with Jquery you can use
$(document.createElement('element'))
At the moment i am using JSON as a result of AJAX and dynamically create all new DOM elements which i need. But here I was thinking - is it right? For example if i need to create a <table> of data is is better to build it with JS or generate it on the server and just append result to the page?
UPDATE
Now i do like this:
jQuery.getJSON(url, function(result){var table = jQuery('<table/>').append([jQuery('<td/>.....
But also can simply like this:
jQuery.get(URL, function(result){jQuery('body').append(result);}.......
there is really no one answer to your question - it all depends on your software type, expected loads, etc.
clearly, moving "rendering" to client side, would reduce the amount of code transmitted between server and client and also less server resources would be used on generate html code (clearly, we are talking about miniature difference). However, it might become really important, if you are talking about thousands of online visitors.
But if you were having thousands of visitors, you would not have asked such question :) So, I guess, you should format all stuff on Server side and void bothering about this question.
It depends on the size of the result. With small results it would make no difference.
But if you are sending a lot of rows for a table a JSON response would be much more efficient than the actual table html code.
Using a template engine like #Arun P Johny said in his comment is a good way to process a JSON result set.
Check underscore templates http://underscorejs.org/#template
There is no right or wrong. It all depends on what suits you best. I personally find JSON to be a good all-purpose format. What you should never do is return the data as HTML to be appended. Try to keep your data free of any structuring that belongs to the presentation layer.
For more information, have a read on Model-View-Controller
The title says it all, but basically I use ajax to get information and I don't know if I should have PHP create the HTML which then gets returned to the client and then javascript just plugs it in or if I should have the server just send all the information through JSON and have javascript (jQuery) create all the html that holds it.
Which one is more efficient?
Thanks
I would say it is better practice to serve only the JSON data. Why?
Well, perhaps, you want to hook up a different type of client to your data service.
Maybe you create a mobile app, and it needs the same data, but wants to display it differently.
If you are providing the HTML markup as well, then now your mobile app has to parse the data it wants out of the HTML structure, rather than just dealing with the data right away.
On an efficiency scale, that depends on what you consider efficient.
For example, it would be efficient from a bandwidth perspective to only send the JSON. However, it would be more efficient from a processing standpoint on the target client to simply give it an HTML string to display.
If you are considering ever having different clients accessing the same data, though, then you want to create a single data interface that serves JSON (in your case), and allow the client to decide how to present that data.
Separation of concerns.
For years I've been reading about XML and I have just not quite grokked it. Most documents I see about it simply explain the syntax (extraordinarily easy to understand) and say that it's portable: I've worked with Unix my whole life so the idea of putting things in plain text to be portable is hardly revolutionary. My specific question is that I have a document (my CV) that I would like to present to web visitors in several formats: as a webpage, as a pdf, or even as plain text. Is XML and Javascript the right approach to take?
What I need is for the document to be easily editable, conversion easy and just easy general upkeep. For example, when I publish a paper, I'd like to take less than five minutes to add the info and then have everything go automatically from there.
Give me your opinions: I also use LaTeX compulsively, so my current approach has been just to have my CV in LaTeX and to convert it to a web-page using LaTeXML. However, I sorta have the feeling that with everybody jumping up and down about XML and Javascript, that there might be something good to learn about it.
I would also like to simplify maintaining my homepage by not duplicating the same footer for every single page that I set up.
Thanks,
Joel
Edit: I'll also take any book recommendations!
I think this is a slight misunderstanding of the combination of JavaScript and XML.
XML, in and of itself is an excellent means of representing data. It's largely human-readable, and easily parsed with libraries in nearly every programming language. That is the main benefit of XML.
Using XML with JavaScript is certainly a solution, but I think it's a matter of the question you're asking. JavaScript can parse XML, and allow you to obtain and manipulate data from your XML document. If you want to grab data from a server without reloading your HTML page (synchronously or asynchronously), then using JavaScript and XML is a valid way to do that.
If you want to, however, display your XML as a webpage, you would likely be better off using XML and XSLT [wikipedia], or perhaps PHP and XPath, to transform the document into browser-readable HTML. On the other hand, you could use nearly any language to convert the XML to a plain-text file, rich text file, or store it in a normalized database.
To sum up, XML is a great way to store data, because it can be used in so many different ways, and by so many different languages. It's an answer to many different questions; you just have to figure out which questions you're asking.
To elaborate on my comment
The transformation to whatever output you desire is depending on how you store your CV on your server and whether you have the possibility to process it on the server. If you store it in XML, you can transform it to desired (binary) output using server based tools - that would for php be pdf and word (on windows server platform) for example. XML would be interesting from a mark-up point of view since it would make it clear where the table of contents, headers, lists of experience and so one would be found.
JavaScript cannot transform something into PDF or word, that has to be done on the server. What javascript can do is to get a text from the server in XML or JSON using AJAX and manipulate this into what the user sees on the screen. For XML that can be done with XSL(T) too. If you want for self-education purposes to use JavaScript, JSON is very nice since it is in my opinion more readable than XML and it creates a populated javascript object with the least work.
Footer in javascript: in the page have
<script type="text/javascript" src="footer.js"></script> and in footer.js, you can for example do
var footerText = 'Here goes whatever you want';
document.write(footerText);
Comparison between XML and JSON
I've got a webpage with browser-side XSLT transformation up and running for years. It's a playground, only some words in german. See how easy it is to build this on heese.net/test. You can switch between "Beispiel" (=Demo) and XSL. The sourcecode of the page in the iframe is the XML. You can do this serverside with 3 lines of PHP-code.
On Javascript: you can use it with XSLT and I show this on my site, but it can't interact. First the XSLT builds an HTML page out of your XML data and after this job is completely done the Javascript in the resultig HTML document begins to work.
Parsing XML with Javascript is a different task.
Please note: this is not exactly same as this question. Although it looks like that, I have some very specific requirements.
In my application, I have two panels to update with a single AJAX request.
Currently, I am sending JSON, and constructing two DOMs in JS and appending them in corresponding places.
This is becoming difficult to maintain, and much processing is happening on the client side. So, I am thinking of sending HTML code snippet.
The problem here is that I have two panels, and with a single AJAX request, how should I bring two different HTML snippets for different panels?
Also: -
1) I am sending the AJAX request periodically after each 30 seconds, and also sending a CRC-32 of the data in the JSON. So, if there is no change in the data I don't have to recreate the DOM.
2) Replacing the old HTML, with new HTML suddenly flickers the page.
3) Each panel can have dynamic number of rows, and I have to attach some events from JavaScript side to each row. For this, it is easier if I have data in JSON format. But if I am switching to HTML snippet, how to do this?
Taconite is something you should look into. It updates multiple HTML blocks with a single request.
http://malsup.com/jquery/taconite/