Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How dangerous is it send HTML in AJAX as opposed to sending JSON and building the HTML? [duplicate]

Possible Duplicate:
Why is it a bad practice to return generated HTML instead of JSON? Or is it?

It seems to me that any interception of this could provide instant trouble because anyone could just send any HTML/script back to the client.

The only reason I'm interested in doing this is because of the huge pain it is for front-end developers every time there's a DOM structure/CSS change so you now have to go figure out where in the Javascript HTML building process you may have to update.

How do you guys deal with this? Are there things I can do to reduce any risk or is ut just straight up bad idea?

like image 449
Ben Crouse Avatar asked Jan 09 '09 17:01

Ben Crouse


2 Answers

I tend to use the following rules:

  1. Request and return HTML for quick snippets, then use client-side (static) Javascript to insert them. Great for alert messages.

  2. Request and return JSON for large datasets. This works great when you want to do filtering, grouping, or sorting on the client side without re-requesting the data in a different form.

  3. Request and return JSON for large datasets, but include the (escaped) HTML snippet for each record in the JSON record. This means more rendering time and more bandwidth use than (2), but can reduce duplication of often complex HTML rendering.

  4. Request and return Javascript, and eval it client-side. This works best for interactions such as hiding, showing, moving, and deleting. It can work for insertions as well, but often type (1) or (5) work better for that.

  5. Request and return Javascript, and eval it client-side, but include escaped HTML in the Javascript so the server is doing the HTML rendering.

I probably use 5 and 1 the most often.

like image 115
James A. Rosen Avatar answered Oct 07 '22 14:10

James A. Rosen


I would seem to me that it would be an even bigger hassle to figure out where in the back-end server that would need to be changed when there's a DOM structure or CSS change.

Keeping all of that in one place (the HTML file) is probably the best reason to limit ajax communication to JSON.

like image 29
James Curran Avatar answered Oct 07 '22 15:10

James Curran