Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML as a result for an AJAX call (PROs an CONs)

What is your opinion (PRO an CONS) about returning HTML code as a result for an AJAX call. It is, if the app creates a new item in a list and it needs some extra parameters or some pattern customization, instead of modify it through JS, we can send it templatized through an AJAX call.

The point is that HTML snippets are sent from the server to the client computer and integrated in the document DOM. Any problem with this approach?

like image 547
Ivan Avatar asked May 24 '11 09:05

Ivan


3 Answers

No problem with it at all, perfectly normal and reasonable thing to do.

There is sometimes a use-case for sending data rather than markup and expanding it with client-side templating, but that's mostly for situations where you're sending a lot of data and so want to keep the size on the wire down. (E.g., a large table where the HTML representation of it is 100k but the raw data in, say, JSON format would only be 10k.) Or when the templating varies depending on client-side conditions. But by and large, perfectly fine to send HTML you then incorporate into the DOM via innerHTML (or any of several libraries' wrappers for it that help you with the odd niggle).

like image 167
T.J. Crowder Avatar answered Oct 23 '22 00:10

T.J. Crowder


This is a common approach.

If you're adding items to a list or replacing the contents of a pod with something completely different this is fine.

This also makes it easier to apply AJAX to existing sites (for example overlays or something) because you can make requests to existing pages and then strip out the bits you don't want.

However, it would be better for updates where only a value is changing then you should perhaps use Json there.

like image 22
Rob Stevenson-Leggett Avatar answered Oct 23 '22 00:10

Rob Stevenson-Leggett


Personally, I almost always choose to receive a JSON response with no markup or formatting applied, but that's just because I like having a really flexible, granular response so I can do whatever I want with the returned data, without having to possibly strip it out of HTML. This is NOT necessarily the easiest or most elegant solution in a lot of cases! :)

like image 2
chrisfrancis27 Avatar answered Oct 23 '22 02:10

chrisfrancis27