Learn when to send the correct format of a response to the view (MVC).

Return HTML from a server response (request), good or bad practice ?

JSON is very versatil and lightweight, that would be enough to make all your responses as JSON, however is a good idea to think how the things will be done, how will be easier and what pass perfect to your project needs.

This article has as main point to clear your mind about a frequent problem, when use json in a response ?

When is a bad practice receive HTML

  • It's a bad practice to receive HTML if you are ending to parse it as data, for example :
$.get("http://url.com/response-service",function(html){
  var myObject = JSON.parse(html);
  console.log(myObject);
});

When is a bad practice receive JSON

  • Use this JSON data to render something on the DOM,instead you should send an html response to be appended to the div that we want.Because you will make this taks a little bit harder for example :
// the response structure will be something like 
// [{article_id:"oijqw8",content:"my content",title:"My title"},{article_id:"oijswee9",content:"my other content",title:"My title 2"}]

$.getJSON("http://myurl.com/response-service",function(data){
    for(var i = 0; i < data.length;i++){
      var article = data[i];
      var html = '<div id="article-'+article.article_id+'">'+article.title+'</div>';
      html += '<div class="content">'+article.content+'</div>';
      $('#list-div').append(html);
    }
});

Many backend developers tend to send portions of html as a response and then render it in the DOM, but they don't do that as a good practice, some developers doesn't master so good the javascript and decide to make all the process in the server as this make the task easy for them.

Points to consider

You need to analyze when every case will fit to your need, sometimes you will need to render that more than once, what would be better ? Process that 1 time on your server and use it in many places (which makes the code more maintainable) or render with javascript in every view.

Return html or json data from a response will not be bad in any case if you know why you send that and how to handle correctly following the good practices.

According to the "performance" that you app needs , for example the load time you may be choosing send json instead of a long html response (for example in mobile devices), as i said before all depends of your need and how you need to handle it.

The time of development is another important thing to consider, note what is easiest for you, make a JSON response and handle with javascript ? or send the html response from the backend and just append it with javascript?.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors