views:

79

answers:

3

What's a better practice? Load data in HTMLformat or JSON-format? When I load HTML i'm able to keep all the html in my php view-file. When i load JSON I have to put it in html elements clientside with javascript.

I know that a 'best-practice-question' isn't suitable for stackoverflow. So a better answer to my question is a list of benefits and disadvantages of both techniques.

+2  A: 

I'd say use JSON whenever you need to process the data client-side, use HTML when you just want to dump it into some container-div.

For example, consider an image viewer, you can fetch a list of preview-image-urls using JSON, create a list of images client side and display them, scroll them around and so on.

On the other hand, if you're performing some action using ajax, and you just want to display a status message (like your table of data in the popup div), I'd suggest rendering the HTML on server side and just display it.

roe
I just want to load a table with data into a popup-div.
Grsm
I've got a popup with a search input. That search text is being posted to the server and a table with mathing data is being returned. Do you think it's not-done when I already add the table-html structure before returning it?
Grsm
+1  A: 

If you later have to do a mobile version, or another client in general, you might benefit from using JSON all over. JSON will also be smaller (might matter or not, depending on your html, the amounts of elements, ...)

Here's a good article on the subject: http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html

deubeulyou
That's quite what I was looking for. I'm reading it now..(i think I'll choose the HTML-method xD)
Grsm
+1  A: 

If you plan to call the data often in the same session, the network traffic and the responsiveness will be better if you just call JSON data. The HTML/JS overhead being in the cache, only data will cross the network from the second call.

However it looks you just need to render a table with TRs/TDs. If you don't call it often, you're better off with a simple HTML dump.

Another consideration is about clearly separating the data and the view, for cleaner code and easier maintenance. A JSON call allows a clear separation between data and HTML. In an HTML dump both are mixed.

I've just answered to another question, it was for JSP, but that may interest you. http://stackoverflow.com/questions/2185915

Mic
I've got my data and html quite separated. Just a few foreach loops to process arrays. (i'm using CodeIgniter)
Grsm