1

I have made a small (test) script that parses a JSON file (I use https://jsonplaceholder.typicode.com in the example below) and makes table rows out of the resulting object.

I am trying to append these rows to a table.

See the jsFiddle HERE.

I get an Unexpected identifier error that I find inexplicable. What am I doing wrong?

UPDATE: See my updated fiddle HERE. Thanks to all that helped.

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • 1
    Please post your code here rather than only linking to an off site paste site. Also please provide an example of the response being returned from the ajax request. – Taplar Nov 24 '17 at 16:00
  • But from your fiddle you are trying to append to the table outside of the ajax request success method. Not only is that an async error, but a scoping error as the variable is locally scoped to the success method. – Taplar Nov 24 '17 at 16:03
  • Check out the answer i have posted – Abid Nawaz Nov 24 '17 at 16:10

2 Answers2

1

You were appended the data wrong way. Replace your this portion of code by this.

var root = 'https://jsonplaceholder.typicode.com';
var tableRow = '';
$.ajax({
  url: root + '/users',
  method: 'GET',
  success: function(data) {
    for (var i = 0; i < data.length; i++) {
      var tableRow = '<tr><td>' + data[i].name + '</td><td>' + data[i].email + '</td><td>' + data[i].email + '</td></tr>';
      $("#dataTable").find('tbody').append(tableRow);
    }
  },
  error: function() {
    var tableRow = '<tr><td>There is no data to display</td></tr>';
    console.log(tableRow);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table" id="dataTable">
  <thead>
    <tr>
      <th>Full Name</th>
      <th>Email</th>
      <th>Address</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
Abid Nawaz
  • 866
  • 6
  • 20
0

just move the part where you set your the html of the table inside the success and error handlers. ajax is async, you are calling the line$("#dataTable tbody").html(tableRow); before you get the actual response, so tableRow is still empty;

    var root = 'https://jsonplaceholder.typicode.com';
var tableRow = '';
$.ajax({
  url: root + '/users',
  method: 'GET',
  success: function(data) {
  var results = '';
    for (var i = 0; i < data.length; i++) {
      results += '<tr><td>' + data[i].name + '</td><td>' + data[i].email + '</td><td>' + data[i].email + '</td></tr>';
    }
          $("#dataTable tbody").html(results);

  },
  error: function() {
    var tableRow = '<tr><td>There is no data to display</td></tr>';
    console.log(tableRow);
    $("#dataTable tbody").html(tableRow);

  }
});

fiddle

ztadic91
  • 2,774
  • 1
  • 15
  • 21