Skip to content Skip to sidebar Skip to footer

Output Json To Html Table

I'm having trouble outputting a JSON to a HTML table within my tab (for part of a javascript/jQuery evening course assignment). Please could someone have a look, and advise what so

Solution 1:

The main issue with your code was that you didn't call any function after the AJAX request completed successfully. You needed at least call drawTable() to populate the data.

However there are several improvements you can make to your code. Firstly, remove jsonp: 'callback'. It's the default value, and also redundant as you're supplying jsonpCallback. You can also then change jsonpCallback to 'drawTable'. This negates the need for the success handler function and means all the request data will be directly provided to your drawTable() function. Lastly, rather than creating DOM elements in memory and appending in each iteration of the loop it's much quicker to build a single string with all the table's HTML and append it once when finalised.

With all that said, try this:

$(document).ready(function() {
  $.ajax({
    url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php",
    dataType: 'jsonp',
    jsonpCallback: 'drawTable'
  });
});

functiondrawTable(data) {
  var html = '';
  for (var i = 0; i < data.length; i++) {
    html += '<tr><td>' + data[i].course + '</td><td>' + data[i].name + '</td><td>' + data[i].price + '</td></tr>';
  }
  $('#table tbody').append(html);
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="table"><thead><tr><th>Course</th><th>Name</th><th>Price</th></tr></thead><tbody></tbody></table>

Note that I reduced the HTML shown here to only the relevant parts.

Solution 2:

// Tabs
$(function() {
    $( "#tabs" ).tabs();
});

// Spanish 
$(document).ready(function(){
    $.ajax({ 
        url:    "http://learn.cf.ac.uk/    webstudent/sem5tl/javascript/assignments/spanish.php", 
    // path to filedataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'jsonpCallback',
        // The var you put on this func will store data success: function (data) {
            alert('success');
            // Call the function passing the data recieveddrawTable(data);
        }               
    });
});

functiondrawTable(data) {
    for (var i = 0; i < data.length; i++) {
        drawRow(data[i]);
    }
}

functiondrawRow(rowData) {
    var row = $("<tr />")
    $("#table").append(row);
    row.append($("<td>" + rowData.course + "</td>"));
    row.append($("<td>" + rowData.name + "</td>"));
    row.append($("<td>" + rowData.price + "</td>"));
}

Post a Comment for "Output Json To Html Table"