0

When my data coming from json and i tried to append row for my datatable with this code. But it didn't work. How can i fix this ?

<table style="width:300px" >
    <thead>
            <th>
                Name
            </th>


    </thead>
    <tbody id="location">


    </tbody>
</table>

    $.ajax(
    {
        type: "GET",
        url: 'http://jsonplaceholder.typicode.com/users',
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function (data) {

            var trHTML = '';
            for (var i = 1; i > data.length; i++) {
                console.log(data[i].name);
                trHTML += '<tr><td><span>' + data[i].name + '</span></td></tr>';

            };
            $('#location tbody').append(trHTML);


        },

        error: function (msg) {

            alert(msg.responseText);
        }
    });

My actual goal is adding row to footable datatable plugin but i can't fix it too.

14
  • Change $('#location tbody').append(trHTML) to $('#location').append(trHTML) Commented Jul 15, 2016 at 11:47
  • 2
    in response change i<data.length Commented Jul 15, 2016 at 11:48
  • Please explain what "didn't work" means. Does it throw a Javascript exception? Does it not draw anything? Do you see messages in the console? Commented Jul 15, 2016 at 11:51
  • 1
    Why would he delete tr in thead? @CiroCorvino Commented Jul 15, 2016 at 11:54
  • 1
    @CiroCorvino. No, <tr> is obligatory for every row (header row or body row). <th> means header cell and <td> body cell Commented Jul 15, 2016 at 11:58

1 Answer 1

1

There are a few issues with your code. Most are already mentioned in the commennts:

1) Your loop does not work because the condition i > data.length is never true. I suggest using jQuery.each(...) to loop over data. Or fix it to i < data.length but then you also have to start with var i = 0.

2) $('#location tbody') does not exist in your html. That would be a tbody element inside an element with the id location. You want $('tbody#location') or just $('#location') as you should not have multiple items with the same id in your html anyway.

3) Your html inside thead is not correct. It will work this way, but it is not clean html.

Hope this list helps. It basically summarises the comments. (Thanks to all you guys here!)

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

1 Comment

Note my edit with var i = 0 in the loop... otherwise you will loose one element of data.

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.