What to return when making an Ajax request
When we return data from an Ajax call, is it better to return a document containing HTML to display on the page, or return XML / JSON data that can be processed?
I know that different circumstances can determine which means "better", but I really want to know which is more appropriate for different circumstances.
I am working on a framework for a large ASP.Net application using jQuery Ajax (forms plugin). My initial thought was to return the data as XML and then process it accordingly. This then increases the processing required in Javascript to fill the page. I am trying to balance flexibility, clarity and simplicity.
Thanks in advance for your knowledge and information.
a source to share
As far as "trying to please everyone is a fast track to mediocrity", wouldn't that have a server-side handler for the AJAX call to generate XML, JSON, or HTML depending on the value of a variable, called for example "format"?
This will allow you to change the format based on the amount of data transferred, the intended processing (client-side), and provide future scalability.
For example, for a very simple query, you might even be happy to just get the text result "true" or "false", so you add "format = simple" to the end of the query. When you ask for a list of items, JSON might be the best option, so it goes "format = json".
I suggest this as it seems to be one of the tricks Google suggests with some of their APIs.
a source to share
Depends on the situation.
1) If you just want to fill the div tag with HTML server (for example for a news site CMS) move the HTML and put it in element.innerHTML. It's simple and effective.
2) If you have more data processing requirements (dynamic client side interface like grid, table, form, etc.), please send JSON or XML.
a source to share
I think it depends on how narrowed down the scope of the update you are trying to do. Obviously, if the area of the page that the information fetched from the server is referring to is anything small, a few controls that need to be updated are best kept concise (like JSON) and handle the client side.
However, if the result of the server-side logic updates a huge portion of the page, it might be convenient to simply re-render that portion of the server and set it as the innerHTML of some container.
a source to share