The Ajax Response: Data (JSON, Xml) or HTML Snippet

The AJAX response: Data (JSON, XML) or HTML snippet?

In most scenarios you need to only send JSON (or XML as appropriate, I am using JSON as an example).

  • If you are sending data such as stock quotes, use JSON.
  • If you want to keep the network layer very lean then send pure JSON data and let the client do the heavy work of adding markup.
  • If the client page is persistent then send JSON. The client can then send a greeting to Person.Name. It can refresh Person.Score or show a form to edit Person.Status, all dealing with just one Person object.
  • If you are exposing web APIs, obviously use JSON so the client can do whatever they want with it.

Now that said, I really dislike generating HTML from JavaScript. It's a maintenance nightmare and I simply don't like mixing the two. So how do you avoid generating the HTML in JavaScript if all you are sending is JSON? If you are dealing with Person(s) object, when you first the render the page, you would render it as such:

...
<div class="person display">
<div class="name"></div>
<div class="status"></div>
<div class="score"></div>
</div>
...

When you get the person data via AJAX, just populate the above DOM structure.

If you wish to display information for multiple Persons then instead of populating the DOM structure directly, you should make a clone of it and then populate it. This way your template stays intact and you can re-use it.

Do you Ajax JSON or HTML?

I would say 'a' is the option you mostly want to stick with.

It's much easier to keep consistent templates server side (you can reuse them in non AJAX scenarios).

Client-side Templating isn't super elegant (if you're going to do it i suggest this: http://ejohn.org/blog/javascript-micro-templating/)

In terms of the styling I would include a minified stylesheet when the page loads not when loading the content.

Why response data from AJAX request comes in error and not success?

The url that you're requesting is sending HTML. Because you specified application/json as the content type, getting HTML as the response would be an error.

Try instead:

$.ajax({
url: "https://jsonblob.com/api/cc73f020-03eb-11eb-909d-095d7b5c02dd",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
console.log("Success: " + data.responseText);
},
error: function(data){
console.log("Error: "+data.responseText);
}
});

That sends a request to their REST api (note /api/ in the URL), which should return JSON.

Using XML for Ajax response vs normal HTML

I think this depends on where you are returning to. Usually if returning to javascript (which i am assuming here) is is beneficial to re turn using JSON format. JSON is simple and lightweight. There are methods in .NET and also jQuery that can parse and serilize/decerlize this.

jQuery.parseJSON( "json" ) 

this will parse a JSON string to a JQuery object

JSON.stringify(your_object) 

this will parse an object into a jquery string you can send up to an ajax call

using System.Web.Script.Serialization;
IList<NewFee> ExistingNewFees = new JavaScriptSerializer().Deserialize<IList<NewFee>>(ExistingNewFeesJSON);

this snippet illustrates deserlizing a json string into a generic list type of a predefined class.

Send an AJAX request and pass JSON data as a response in html

Just store the json response received from server script in response & then loop around the json response to get the corresponding data(skill & status).

Since you have the code to update the DOM with related values already,rest of the code should work as intended.

JS Code:

 var response;
$.post(
SITE_URL+"mycontroller/myAction",
{
start_date : '01-JUL-15',
end_date : '31-JUL-15',
resource_ids : '100,200',
project_id : 10
},
function(json){
processResponse(json);
}, 'json');

....
....
function processResponse(response) {
var selResId = jQuery('#grid').jqGrid('getGridParam', 'selarrrow');
resourceLength = selResId.length;

if (resourceLength > 0) {
var names = [];
var j=1;
for (var i=0, il=selResId.length; i < il; i++) {
var skill = response[i].skill;
var status = response[i].status;
var name = jQuery('#grid').jqGrid('getCell', selResId[i], 'USER_NAME');

$('#addr'+j).html("<td style='text-align:center;'>"+name+"</td><td style='text-align:center;'>"+skill+"</td><td>"+status+"</td>");
$('#resource_table').append('<tr id="addr'+(j+1)+'"></tr>');
j++;
}
}

At the same time, you need to echo the response data which you need to send it to client application eg., $.post.

PHP SCRIPT

//response should contain the above json
<?php echo response; ?>

Javascript - Json or html?

If you want the user be able to switch between different views, and this is data that can simply be included on page load, then just include onload then hide/show or load as json and then populate as needed.

If this is a very simple request that needs to be updated as needed and you don't plan on other similar needs in your app then just return html.

However if you are making a request that submits data or performs some action, I am a fan of returning a consistent json response with error boolean, error message and content/data elements.

Return JSON instead of XML from web service using Ajax while 'contentType' is 'false'

After beating my head against the wall for many days, I finally figured out the solution which belongs to Ajay, here.

While nothing else has helped me, I used this and it worked perfectly:

  1. Change the return type of your method to void.

  2. And then instead of writing the return statement in your method, you need to do this to return a value:

    Context.Response.ContentType = "application/json; charset=utf-8";
    Context.Response.Write(new JavaScriptSerializer().Serialize(new YourData()));
  3. After that you can easily get the result using the success event of the Ajax call:

    success: function (result) {
    alert(result.Property); // Note: Don't use result.d here
    }

Best practices for returning and displaying data from AJAX calls

I think it ends up depending on your app.

Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.

However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.

Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.



Related Topics



Leave a reply



Submit