Design – Why Returning HTML Instead of JSON is Problematic

ajaxdesign

When I first started learning PHP (about 5 or 6 years ago) I learned about Ajax, and I went through "the phases":

  1. Your server returns HTML data and you put it inside a DOM's innerHTML
  2. You learn about data transfer formats such as XML (and say "oooh so THAT'S what it's used for) and then JSON.
  3. You return JSON and build your UI using vanilla JavaScript code
  4. You move to jQuery
  5. You learn about APIs, headers, HTTP status codes, REST, CORS and Bootstrap
  6. You learn SPA, and frontend frameworks (React, Vue.js, and AngularJS) and the JSON API standard.
  7. You receive some enterprise legacy code and upon inspecting it, find that they do what's described in step 1.

As I worked with this legacy codebase, I didn't even consider that it could return HTML (I mean, we're professionals now, right?), so I had a hard time looking for the JSON endpoint that was returning the data that the Ajax calls populate. It was not until I asked "the programmer" that he told me it was returning HTML and being appended directly to the DOM with innerHTML.

Of course, this was hard to accept. I started thinking of ways to refactor this into JSON endpoints, thinking about unit testing the endpoints and so on. However, this codebase has no tests. Not a single one. And it's over 200k lines. Of course one of my tasks includes proposing approaches for testing the whole thing, but at the moment we're not tackling that yet.

So I'm nowhere, in a corner, wondering: if we have no tests whatsoever, so we have no particular reason to create this JSON endpoint (since it's not "reusable": it literally returns data that only fits on that part of the application, but I think this was already implied since it… returns HTML data).

What exactly is wrong with doing this?

Best Answer

What's actually wrong with an endpoint returning HTML rather than JSON data?

Nothing, really. Each application has different requirements, and it may be that your application wasn't designed to be a SPA.

It may be that these beautiful frameworks that you cited (Angular, Vue, React, etc...) weren't available at development time, or weren't "approved" enterprisey thingies to be used in your organization.

I'm gonna tell you this: an endpoint that returns HTML reduces your dependency on JavaScript libraries and reduces the load on the user's browser since it won't need to interpret/execute JS code to create DOM objects - the HTML is already there, it's just a matter of parsing the elements and rendering them. Of course, this means we're talking about a reasonable amount of data. 10 megabytes of HTML data isn't reasonable.

But since there's nothing wrong with returning HTML, what you are losing by not using JSON/XML is basically the possibility of using your endpoint as an API. And here lies the biggest question: does it really need to be an API?

Related: Is it OK to return HTML from a JSON API?

Related Topic