Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery ajax - return json or plain html better

When the time return from ajax, I should return as json encode, and use jquery.parseJSON and use document.createElement and append the data inside the Element that just created.

or it is better to return as html text?

example,

<div id="contentcontainer"></div>

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John",
   success: function(msg){
     msgObj = jquery.parseJSON(msg);
     var div = document.createElement('div');
     div.style.color="red";
     $(div).append(msgObj.name);
     $('#contentcontainer').append(div);
   }
 });

 //some.php
 if($_POST['name']){
    echo json_encode( array('name'=>$_POST['name']) );
 }

OR I should do like this?

<div id="contentcontainer"></div>

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John",
   success: function(msg){ 
     $('#contentcontainer').append(msg);
   }
 });

 //some.php
 if($_POST['name']){
    echo '<div style="color:red">'.$_POST['name'].'</div>';
 }

Ammended... sorry for my bad grammar

Of course, this is just a example, real case it would have a lot of data, may be in html table format.

Of course, this is just a example, real case it would have a lot of data.

if it has a lot of data, then I need to write a lot of document.createElement(). and it consumes time to write like this document.createElement('table'); document.createElement('tr');

instead of (Return as HTML and just append in the container)

For me I think second format( return HTML ) is easier.

But not sure for the performance wise, which is better?

Please advise.

like image 267
cww Avatar asked Nov 13 '10 05:11

cww


1 Answers

Both Sébastien and Zain have valid points. It depends what kind of performance you're talking about.

If you want to reduce your server's bandwidth, then you should return JSON and create your display using client-side javascript.

However if your dataset is large, on most machines creating your display client-side could lag the browser and cause the UI to become unresponsive. If that is important to you then you might consider returning HTML from the server.

like image 167
Calvin Avatar answered Sep 27 '22 18:09

Calvin