0

I need to insert some values ​​in a table. All values are contained in a returned array from an Ajax/php request like this:

var data = [];

//Consider that the number of the object (in this case only 3) obtained from the server are equal to the number of rows in tbody (6 rows in tbody = 6 object from server).

data[0] = {From: '01/01/2012', To: '01/01/2013', Interest: 80.00, Residual: 0, Capital: 1000.00, Days: 366};
data[1] = {From: '01/01/2013', To: '01/01/2014', Interest: 85.00, Residual: 0, Capital: 980.00, Days: 365};
data[2] = {From: '01/01/2014', To: '29/04/2014', Interest: 20.00, Residual: 75.00, Capital: 980.00, Days: 118};

It's a bit tricky to explain how the values must to be inserted in the table, so I created a fiddle with the result I would like to get. I do not expect you to give me the final result (of course, would be welcome :) ), but at least some idea from which to start.

FIDDLE

**EDIT

I assigned id to cells and now all values are right inserted. That's the updated fiddle, do you think code can be written more elegantly?

UPDATE FIDDLE

2
  • 1
    start with assigning respective id's to cells if that is in your control. Do the required calculation and fill the respective cells. Commented Apr 29, 2014 at 11:07
  • I'm trying your suggestion Commented Apr 29, 2014 at 11:48

1 Answer 1

1

I can see the data returned from ajax/php request is in JSON format. So to insert them in HTML table you can use JQuery.

Example (as you given sample data):

function buildDataTableHtml(data){
    var tableHtml = "<table><tr>";
    tableHtml += "<th>From</th>";
    tableHtml += "<th>To</th>";
    tableHtml += "<th>Interest</th>";
    tableHtml += "<th>Residual</th>";
    tableHtml += "<th>Capital</th>";
    tableHtml += "<th>Days</th>";
    tableHtml += "</tr>";

    $.each(data, function(i, v){
        tableHtml += "<tr>";
        tableHtml += "<td>" + v.From + "</td>";
        tableHtml += "<td>" + v.To + "</td>";
        tableHtml += "<td>" + v.Interest + "</td>";
        tableHtml += "<td>" + v.Residual + "</td>";
        tableHtml += "<td>" + v.Capital + "</td>";
        tableHtml += "<td>" + v.Days + "</td>";
        tableHtml += "</tr>";
    });
    tableHtml += "</table>";

    return tableHtml;
}

If you use this JavaScript function (along with JQuery) then this function will return the HTML of a table you wanted. Hope this will be helpful for you

NOTE: I just write it down in answer box, didn't try to make sure this is working. But hope the code will work. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.