29

I've got a fairly ajax heavy site and some 3k html formatted pages are inserted into the DOM from ajax requests.

What I have been doing is taking the html responses and just inserting the whole thing using jQuery.

My other option is to output in xml (or possibly json) and then parse the document and insert it into the page.

I've noticed it seems that most larger site do things the json/xml way. Google Mail returns xml rather than formatted html.

Is this due to performance? or is there another reason to use xml/json vs just retrieving html?

From a javascript standpoint, it would seem injecting direct html is simplest. In jQuery I just do this

jQuery.ajax({
    type: "POST",
    url: "getpage.php",
    data: requestData,
    success: function(response) {
        jQuery('div#putItHear').html(response);
    }

with an xml/json response I would have to do

jQuery.ajax({
    type: "POST",
    url: "getpage.php",
    data: requestData,
    success: function(xml) {
        $("message",xml).each(function(id) { 
            message = $("message",xml).get(id); 
            $("#messagewindow").prepend("<b>" + $("author",message).text() + 
            "</b>: " + $("text",message).text() + 
            "<br />"); 
        });
    }
});

clearly not as efficient from a code standpoint, and I can't expect that it is better browser performance, so why do things the second way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
pedalpete
  • 21,076
  • 45
  • 128
  • 239

8 Answers8

16

Returning JSON/XML gives the application more freedom compared to returning HTML, and requires less specific knowledge in different fields (data vs markup).

Since the data is still just data, you leave the choice of how to display it to the client side of things. This allows a lot of the code to be executed on the client side instead of on the server - the server side needs to know only about data structures and nothing about markup. All the programmer needs to know is how to deliver data structures.

The client implementation only needs to know about how to display the data structures returned by the server, and doesn't need to worry about how these structures actually get build. All the programmer needs to know is how to display data structures.

If another client is to be build (that doesn't use HTML as a markup language), all the server components can be reused. The same goes for building another server implementation.

ylebre
  • 3,100
  • 1
  • 18
  • 14
  • i've actually got an xml version for these purposes. i'm more concerned about client handling the input of html vs xml/json. it isn't much different for the server to create xml vs html. but if I know 90% of the requests are going to be coming from this client, then why go to xml first? – pedalpete Jul 18 '09 at 19:31
  • XML is a bit easier to build, since you don't need to think about how it will be displayed. All you need to worry about at that point is to make sure you have all the data you need - and that the data is in a usable structure. If you know how your XML data structure is going to look at the start of a project, you can easily work on the project with 2 teams - one for gathering the data from the sources and pouring it into the XML. The other team can work with the XML mockup to work on the presentation of the data. Since the teams can work independantly, they can work parallel, thus faster. – ylebre Jul 18 '09 at 19:40
6

It will normally reduce the amount of data transferred and therefore improve transfer speed. As anything over-the-wire is normally the bottleneck in a process reducing the transfer time will reduce the total time taken to perform the process, improving user experience.

Garry Shutler
  • 32,260
  • 12
  • 84
  • 119
  • 2
    this gets really at the heart of the issue Garry. Though it also opens it to further debate. with 2K coming down the line, i'm wondering where the performance hit is going to come? is it from coming down the pipe? or is it from inserting a chuck verses parsing through the json/xml and then inserting one-by-one – pedalpete Jul 18 '09 at 19:52
  • 1
    It's also useful to note that when jQuery gets html back from AJAX, if it's a HTML page there's a lot of data there that jQuery can't parse. Since jQuery's method for constructing the new DOM nodes is to hold them inside a div, elements like html, head, body, etc. are invalid and ignored. This can mean you're sending back a lot of wasted data over the wire. – Gabriel Hurley Jul 18 '09 at 20:12
4

Here are a few pros for sending JSON/XML instead of HTML:

  1. If the data is going to ever be used outside of your application HTML might be harder to parse and fit into other structure
  2. JSON can be directly embedded in script tags which allows cross domain AJAX scenarios
  3. JSON/XML preserves the separation of concerns between the server side scripts and views
  4. Reduces bandwidth
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

You should check out Pure, a templating tool to generate HTML from JSON data.

Massimo Fazzolari
  • 5,185
  • 3
  • 27
  • 36
1

In some cases, AJAX responses need to return more information than just the HTML to be displayed. For example, let's say you are returning a list of the first twenty items from a search. You may need to return the total number of search results to be displayed somewhere else in the DOM. You could try piggybacking the total count in a hidden div, but that can get messy. With JSON, the total count can simply be a field value a structured JSON response.

James Lawruk
  • 30,112
  • 19
  • 130
  • 137
1

Generally JSON is a more efficient way to retrieve data via ajax as the same data in XML is a lot larger. JSON is also more easily consumed by your client side Javascript. However, if you're retrieving pure HTML content I would likely do as you suggest. Although, If you really needed to, you could embed your HTML content within a JSON string and get the best of both worlds

Steve Mc
  • 3,433
  • 26
  • 35
1

I'm currently wrestling with this decision too and it didn't quite click until I saw how Darin boiled it down:

"If the data is going to ever be used outside of your application HTML might be harder to parse and fit into other structure"

I think a lot of it is where/how the data is going. If it's a one-off application that doesn't need to share/send data anywhere else, then spitting back pure HTML is fine, even if it does weigh more.

Personally, if there is complex HTML to be wrapped around the data, I just spit back the HTML and drop it in. jQuery is sweet and all, but building HTML with Javascript is often a pain. But it's a balance game.

  • Despite how flawed the DOM is, I think it's pretty easy to traverse the document via javascript. For instance, with PHP you'd have to put some PHP code exactly where you want the output to show up - from JavaScript you can select nodes and gracefully(or not so much) dump data into various elements across the page from the same block of code. – Charles D Pantoga Mar 18 '13 at 01:13
0

To me it boils down to this:

It's for many of us, much less work to use a server side, mature, template engine that we're accustomed to, to generate html and send it down the pipe, than using a bunch of javascript code to generate HTML client side. Yes, there are some templating engines for javascript now which may mitigate it somewhat.

Since I already separate model, logic and views server side, there is no argument in having yet another separation. JSON is a view, HTML is another view.

And lets face it; both HTML/AJAX and JSON/AJAX are many times better than full page over the pipe.

The final thing you perhaps need to think about is; if you're going to be search engine friendly - you might have to generate the HTML server side any way (the old degrade gracefully mantra).

I usually do a combination. If there is client side logic, I use JSON - else I use HTML. Notifications and autocomplete special fields are sent via JSON.

frodeborli
  • 1,537
  • 1
  • 21
  • 30
  • 1
    consider this question was asked in 2009 (6 years ago) it probably isn't relevant anymore. Your time is probably better spent answering more current questions. – pedalpete Feb 13 '15 at 01:13