Ben Carey
Ben Carey

Reputation: 16968

Including HTML in an AJAX JSON response

Brief Explanation

I have a form that is currently being loaded via AJAX. Ideally I would use the jQuery load() method, however, this request is slightly more complex as I also need to retrieve individual properties instead of just one large HTML chunk.

So, my script looks something like this (simplified):

$.ajax({
    url: url,
    dataType: 'json',
    success: function(data){
        // Set the width of the form
        $('.form').css({
            width: data.width
        })
        // Load the form into the popup
        $('.form').html(data.html);
    }
});

My Question

I am unsure whether including my HTML markup in the JSON response is such a good idea...

  1. Am I correct in thinking the above?
  2. Are there any other alternatives?
  3. Will I run into limits with large chunks of html stored in a JSON request?

Please Note

I am of course aware that I could build the markup using javascript, however, as there are several forms and all of which are quite large, it it much easier to build the form server side. Not to mention the fact it makes it much easier to debug/develop/maintain...

Furthermore, my site is currently VERY javascript heavy so I would like to minimise as much of the js needed as I possibly can.

Upvotes: 2

Views: 1369

Answers (1)

Nicolas Straub
Nicolas Straub

Reputation: 3411

  1. You can include the html in a json object, just make sure to escape all quotes and other special characters.
  2. You're probably better off with two requests, one that loads the html form and another that gets the data you need. This will make for cleaner, more maintainable code.

Upvotes: 4

Related Questions