1

I'm now working with API calls currectly, so most the requests are done through ajax call. As you can expect, both the data sent to server and data received from server will be xml data. I've successfully able to dynamically construct the xml data during the sign up process and during post requests. By utilising JaxB, I've done the necessary steps in server.

Now I've to get the data as xml from server if a user needs to view a ceertain resource. Like before, I'm using jaxb to convert Java object into xml data and I'm getting the xml data in success function of Javascript. There are lot of examples and questions present on converting this xml data into user viewable form.

By my main goal is to make every function Dynamic, Consider now I'm going to show the list of users to admin, I can use these examples to convert my xml data into tables.

Display JSON Data in HTML Table

populate jquery data table with returned json data

If I'm doing like that, I've to manually write the same process with some modification based on table fields for every list view. This is a bad practise if I'm going to copy paste the same code with some modifications for 10 list views. I would like to make the xml to table conversion as a common function for any number of tables no matter how many fields are present in it.

I'm getting the xml data from server as String. So I've converted it to recognizable xmlData using following code.

var xmlData = jQuery.parseXML(data);    //data is the xml String which I'm getting from server

//Converting xmlData into JSON Objects
var containerTag = myTag    //I can get this from - document.getElementById("tableId").name
var output = new Array( );  
var rawData = xmlData.getElementsByTagName(containerTag)[0];
var i, j, oneRecord, oneObject;
for (i = 0; i < rawData.childNodes.length; i++) {
    if (rawData.childNodes[i].nodeType == 1) {
        oneRecord = rawData.childNodes[i];
        oneObject = output[output.length] = new Object( );
        for (j = 0; j < oneRecord.childNodes.length; j++) {
            if (oneRecord.childNodes[j].nodeType == 1) {
            oneObject[oneRecord.childNodes[j].tagName] = oneRecord.childNodes[j].firstChild.nodeValue;    
            }
        }
    }
}

By displaying the data as console.log(output[0]); , I'm getting my real data. But I searched to use this information to populate it in table, most of them suggests to do it like

.fieldname1
.fieldname2

and so on which is not I'm expecting to. I've been learning Javascript now a days, but I dont know how to make the process common for all tables irrespective of no of fileds.

Note: I'm using jquery datatables.

Just a thought comes up in my head. Is it possible to just give the Json object to jquery datatables and it'll do the remaining process..?

For reference, this is my xml data

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
    <user>
        <id>1</id>
        <username>user1</username>
        <email>email1</email>
        <status>active</status>
    </user>
    <user>
        <id>2</id>
        <username>user2</username>
        <email>email2</email>
        <status>active</status>
    </user>
    <user>
        <id>3</id>
        <username>user3</username>
        <email>email3</email>
        <status>inactive</status>
    </user>
</Users>

This is the Json object

Object { id: "1", username: "user1", email: "email1", status: "active" }  //output[0]
Object { id: "2", username: "user2", email: "email2", status: "active" }  //output[1] 
Object { id: "3", username: "user3", email: "email3", status: "inactive" }  //output[2]
Community
  • 1
  • 1
The Coder
  • 2,562
  • 5
  • 33
  • 62

2 Answers2

2

As @epascarello said only a cleaner way is to create tr's dinamically based on the output array index and td's based on the keys from the output[i] -json. Using jquery an example should look like this.

var table = $('<table></table>');
for(var i=0; i < output.length; i++) {
   var tr = $('<tr></tr>');
   for(var key in output[i]) {
     var td = $('<td></td>');
     td.attr('class', key);
     td.text(output[i][key]);
     tr.append(td);
   }
   table.append(tr);
}
$('body').append(table);

Example here: http://jsfiddle.net/atrifan/4zfs57m8/3

atrifan
  • 172
  • 5
  • That was a great example atrifan, but what if I decide to add a column called "action" to every row (not at the end of each row, but at the middle of each row), for example I want to put edit and delete button in that "action" column for every row.. I doubt that I should have to use for each in that case.. – The Coder Feb 04 '15 at 19:14
  • 1
    Well with a little bit of editing you get this: http://jsfiddle.net/atrifan/4zfs57m8/ – atrifan Feb 04 '15 at 19:35
  • Putting your created td in an array of tds, and afterwards using the splice method on a position(calculated or hardcoded in your case the middle) tds.splice(position, 0 , yourDefaultTdElement). Iterate than over the tds array and insert the elements inside your tr and you're done. See the above example. – atrifan Feb 04 '15 at 19:45
  • Thanks a lot atrifan. That's what I needed. Rather than creating the entire table manually, it's more simple approach.. – The Coder Feb 04 '15 at 19:49
  • I've altered your example code to meet my needs, but I'm using jquery datatables. I already have ......
    hardcoded in the html page. I need only the to be added below the .. I've entirely deleted from html and I tried to append the js result to table as $('table').append(table); The rows get appended, but the problem, it's a jquery datatables, there is one row above the which is showing as No data available in table. I'm trying every possibility, if you know how to solve this, kindly help me..
    – The Coder Feb 04 '15 at 21:33
  • Updated the jsfiddle to meet your purpose check out the html part where you have the predefined
    just got the tbody from the table and added inside. I added an id to my example table and you could do the same if you have more tables in your html file. See example: http://jsfiddle.net/atrifan/nhjkcg8h/2
    – atrifan Feb 04 '15 at 21:41
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/70266/discussion-between-user1354678-and-atrifan). – The Coder Feb 04 '15 at 21:53
1

you can even try this

var output = [{id: 1, name: 'Alex', phone: '000'}, {id: 2, name: 'Paul', phone: '010'}];

var stBldr='';
stBldr+='<table border=1>';
$.each(output,function(i,v){
stBldr+='<tr>';
stBldr+='<td>'+$(v)[0].id+'</td><td>'+$(v)[0].name+'</td><td>'+$(v)[0].phone+'</td>';
stBldr+='</tr>';
});
stBldr+='</table>';

var str=$(stBldr);
$('body').append(str);

DEMO

Nadeemmnn Mohd
  • 713
  • 5
  • 14