Skip to content

Ajax with HTML or JSON

April 5, 2012

Recently a poster on the asp.net forums asked about the difference between returning HTML or JSON from Ajax calls. Here was my answer:

airic82

Well, ya. But working doesn’t always mean its following best practices.

Sinful term! “Best practice” requires context. Usually the answer is “it depends” and thus there’s rarely “the one and only one best practice” which is what people are usually looking for.

airic82

I guess the piece I’m missing is the difference between returning HTML and JSON. Maybe there really isn’t any difference, but I’d think there was since we can specify a difference. Thanks for your help, man!

Ah, ok… so yes, there’s a difference there. If your Ajax call returns HTML this means you’ve done the UI “work” (so to speak) on the server (using WebForms, Razor, whatever) and then that HTML is returned to the browser and merged into the DOM (and merged into the DOM in one place). This might work fine, but sometimes things are more complex and this is where returning JSON might make more sense.

Returning JSON means the UI “work” (rendering) is done in JavaScript/jQuery client-side. The network bandwith is much less (JSON is more compact than HTML [or XML for that matter]). But the downside is this requires more JavaScript to do the rendering (but less server side coding). Returning JSON and thus allowing the JavaScript to build the UI from the result also allows for more complex UIs — imagine where the results means you have to update multiple elements. That’s hard to do if your’e returning a single block of HTML from the server. With JSON the client-side JavaScript can use that JSON data to update multiple parts of the UI. Also, if the client is a mobile device then it’s preferred that you return JSON as to minimize bandwith to save battery on the device.

Anyway, the answer is “it depends” — that’s the consulting answer :)

 

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: