views:

46

answers:

2

Hi all,

I have a few pages with an heavy javascript usage (e.g. sorting and filtering of a dataset).

The typical usage is to display a list of complex items (usually rendered as <li> with some HTML inside): the user can delete, edit or add items with specific forms. Since the items are complex, I keep an array of javascript objects to perform any sort of operations, such as validate the user input before performing any action.

The user's action and details are sent to the server via asynchronous calls: after the outcome arrives I have to update both the HTML and the javascript array.

I use this hack: the server returns the json-encoded data structure and the updated HTML as a single string. Upon data arrival, some javascript code splits the response and parses the first chunk as json (updating the array) and puts the second chunk in the inner html of the container, replacing the previous content.

I don't want to generate the HTML from the data structure, since it is not a one-man application, and the web designers change the HTML layout quite often (and independently). Neither I want to recreate the data structure from the HTML (too complex and error-prone).

This system works quite nicely, having some problems only with big content, is cross-browser (is built on jQuery) and doesn't seem to have big performance issues.

The question is: am I missing something subtle (or maybe obvious) that makes this solution bad? Does it exists a simpler and better solution around?

By the way, the server runs PHP.

Thank you.

+4  A: 

Why don't you return the HTML string as part of the JSON? This way, your output is cleaner.

starskythehutch
+2  A: 

So presumably you have two variables: a HTML string ($html_string) and an PHP array of information which will be sent in JSON format ($array_of_info). Then:

$a = array(
  'html' => $html_string,
  'json' => $array_of_info
);
header('Content-Type: application/json');
echo json_encode($a);
TRiG
This is slightly longer than simply concatenating the HTML and JSON strings, but the parsing on the client side should be easier. And probably faster.
TRiG
and less error prone
Gutzofter