Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically updating html table with JSON using jQuery for complex object

Tags:

json

jquery

I am still new to JSON/jQuery.

I need some quick guidance on how to dynamically populate Html table on the client. My table has fixed columns, but rows grow dynamically depending on data retreived.

Say I have a Web Method on the server (GetActiveUsers) that is returning, say n- users. I am using this sql:

select userId, Title,Surname,FirstName from Users where status=1

Please give me sample code

Edit

I have solution for this on this post here Thanks guys

like image 669
Julius A Avatar asked May 24 '26 14:05

Julius A


1 Answers

This is a perfect application of jQote THE jQuery javascript templating engine. You can fetch it from here: http://aefxx.com/jquery-plugin/jqote.

As an example consider the following:

// Example of your json data ... an array of user objects
[{
    "Title": "Dr.",
    "Surname": "House",
    "Firstname": "Geronimo"
  },
  {
    "Title": "Mr.",
    "Surname": "Franklin",
    "Firstname": "Benjamin"
  }
]

Now here's the template you would define in your HTML (or whatever output file you have):

<script type="text/html" id="template">
    <![CDATA[
        <tr>
            <td class="no"><%= j+1 %></td>
            <td class="title"><%= this.Title %></td>
            <td class="user"><%= this.Firstname + " " + this.Surname %></td>
        </tr>
    ]]>
</script>

So, we're almost done. Let's define our containing table and call jQote on the json data to magically fill the table.

... your markup ...

<table id="users"></table>

... more markup ...

<script type="text/javascript">
    var jsondata = xxx // get your data somehow

    // Now call jQote on the template providing your json data
    $('#template').jqote(jsondata).appendTo($('#users'));
</script>

That's all (well it's just the beginning, jQote is way more powerfull than I could tell you here).

Hope you like it, give it a try.

BTW: The use of as your template's container is perfectly legal markup. And browsers will not display it in any case.

like image 69
aefxx Avatar answered May 27 '26 02:05

aefxx