AJAX and JSON – How to Return Generated HTML and a Response

ajaxjson

My web application will use AJAX calls often and so I have set up some JavaScript to handle "messages" or "responses". These responses are returned (from my ASP.NET application) as JSON objects that act as feedback once a function is complete.

Suppose my responses have three basic elements.

  • Type (error, warning, info, success)
  • Title
  • Message

For example

Save unsuccessful

Your data was not saved because of XYZ.

Sometimes, however, I want my function to generate and return some HTML. That's easy enough, but what if I still want to return a message to the user (or some other JSON)?

  • Should I return the HTML as part of the JSON?
  • Should I only return one or the other?
  • Should I return HTML, then make another AJAX call for the response?
  • Should I return HTML and store the response in data- tags?

Can someone point me in the right direction?

Best Answer

Should I return HTML, then make another AJAX call for the response?

Unless you have some compelling reason not to (there aren't any I can think of), you should definitely favor minimizing the number of calls. Each call has the overhead of URL resolution/etc. and if you're just getting the same data you'd send anyway in the single call, there's no reason for that waste.

Should I return the HTML as part of the JSON?

Returning HTML in JSON is fine, if you're using jQuery (or even naked DOM access), it's easy to update the HTML of an element. If you don't need the HTML message, that property can be null or omitted entirely, so it wouldn't be wasteful to include it only in the cases where you need it.

Should I only return one or the other?

From the ASP.NET function? I think it's probably best to include the HTML property as part of a standard protocol. For example, I have 3 standard properties from all AJAX calls: Success, ErrorMessage, ErrorTitle. This keeps it easier for someone to work with as well since they can rely on those being there all the time and act accordingly.

Should I return HTML and store the response in data- tags?

You might have a use case where this makes sense, but I think in general, it makes more sense to have JS functions for responding to the standard message protocol instead. This way it allows the caller more control over how, when, where, etc. the messages display. You can also come up with sensible defaults that can be overridden if there's a need.