views:

223

answers:

7

I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that.

My question is what is the best practice for returning the info and then displaying it?

  • Return JSON object and then create html on the fly with js and display the data?
  • Return JSON object and then put that data in already created containers for the data on the page?
  • Return pure html from the server and just put that on the page?

I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason.

I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.

A: 

Returning pure HTML is the best solution. For the most part gzip should neutralize any difference in bandwidth, and rendering via javascript on the client can be slow if the client is a crappy machine. Finally, writing javascript to render HTML is hard to work with compared to using something nice like a view if you use MVC.

RedFilter
this is far from 'best', since mixes data with presentation. a lot cleaner is to use templates in the HTML and populate them with the data
Javier
Huh? Nothing is getting mixed, it is cleanly separated server-side via MVC in my approach.
RedFilter
+5  A: 

I think it ends up depending on your app.

Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.

However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.

Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.

Tom Hubbard
A: 

This came up recently and possible a dupe: The AJAX response: Data (JSON, XML) or HTML snippet?.

If you are going to be creating HTML then you may as well be returning HTML directly and inject it into the DOM. However, there are times you need to work with objects which is where JSON comes in handy.

If you return a Person object for example then you can greet Person.Name and show Person.Preferences which is really handy. It depends on your design but the general considerations should be to keep HTML out of Javascript unless you're building RIA.

aleemb
Have you just included the link to THIS question in your answer?
dalbaeb
linked to the proper post. too many windows open =)
aleemb
+4  A: 

This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).

dalbaeb
Exactly. JSON is beautiful.
KyleFarris
A: 

I have used all three and have come to the conclusion that returning HTML is better when introducing new elements to a page.

My experiance is that when building HTML with javascript I am usually replicating work that will have already have been done for the non javascript user journey.

I still prefer parsing json for updating existing elements or creating javascript only functionality. I tell myself this for bandwidth, but I think it just because I love javascript.

As a forth option, I read a great post about how Flickr deal with vast quantities of data with string concatination. Basically just parse a big o' string down the pipe and chop it up on the client. This significantly reduces the on the server, with only a marginal increase on the client.

kim3er
+1  A: 

The "possible action beyond that" part of your question makes a big difference. If you need to do other things with the data besides display it, returning as JSON is a clearly better option because you can work with the data as a native JavaScript object instead of having to traverse the HTML DOM. If all you ever intend to do is display it, I don't see any reason to go through the trouble of building that display in JavaScript; just build the HTML in your presentation layer on the server.

John M Gant
+1  A: 

I think you're missing a perfectly valid option, one which I use often. This is my typical schema and it has yet to fail me... :-)

Here's the basic jQuery template I use:

$(function() {
    $.getJSON('/some/page',{foo:bar,bar:foo},function(json) {
        if(json.outcome == 'success') {
            $('body').prepend(json.html);
        } else {
            // Somehow let the user know why it didn't work
            alert(json.error);
        }
    });
});

Here's the basic backend (PHP in my case) structure I use:

<?php // Page: '/some/page'

/* Blah Blah Blah... do whatever needs to be done... */

// If everything turns out okay (assuming '$output' is the HTML 
// you want to display...
echo json_encode(array('outcome'=>'success','html'=>$output));

// If something goes wrong... just do:
echo json_encode(array('outcome'=>'error','error'=>'Uh oh... something is broken'));

Naturally, you'll want to be more specific with your error by putting them into some variable or something. But, you should get the idea. Also, of course you can add more information to the json output. You can have some pre-made HTML and also some other information like a 'success notice' or a new class name for some element, I dunno... whatever... the possibilities are endless.

Anyways, the reason I choose this route is because it's usually faster (based on my experience) to append pre-made HTML to the DOM rather than looping over JSON and inserting the stuff unless it's just, like, a bit of text to replace into an element. But, the method I've shown is, IMO, the best of both worlds. You can attach HTML as a string to one of the JSON properties.

Happy jQuerying :-)

KyleFarris