Output JSON to html table - javascript

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 sort of amendments I would have to make to output in a table format?
I get the success alert, but the table doesn't populate.
Thanks.
// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/webstudent/sem5tl/javascript/assignments/spanish.php", // path to file
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
success: function () {
alert('success');
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(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>"));
}
And the HTML:
<div id="tabs">
<ol start="50">
<li>
Italian
</li>
<li>
Spanish
</li>
</ol>
<p id="tab-1"></p>
<p id="tab-2">
<table id='table'>
<thead>
<tr>
<th>Course</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</p>
<p id="tab-3"></p>
</div>

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'
});
});
function drawTable(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);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="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.

// Tabs
$(function() {
$( "#tabs" ).tabs();
});
// Spanish
$(document).ready(function(){
$.ajax({
url: "http://learn.cf.ac.uk/ webstudent/sem5tl/javascript/assignments/spanish.php",
// path to file
dataType: '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 recieved
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(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>"));
}

Related

Html Table row id checkbox

I would like to have the database table id on each row as checkbox value of a dynamic html table
I am using ajax to fetch data from mysql database and create a new variable as html text to append on tbody of table
Code of HTML
<div class="col-sm-6" id="ftbl">
<label for="urbandata">View urban data</label>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Check</th>
<th>ID</th>
<th>Type</th>
<th>Master</th>
<th>Slave</th>
<th>Orbit</th>
<th>Mode</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Code of JS
$.ajax({
url: "fetchurban.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" id="checkview" onclick="QuickView()" name="'+ item.TblID +'"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><span class="glyphicon glyphicon-download"> </span><span class="glyphicon glyphicon-cloud-download"></span></td></tr>' ;
});
$('#ftbl tbody').append(trHTML);
}
}
})
})
If the user select the checkbox I would like to have the id of database table.
Now with this code I have the same id to all rows of table
You could set the identifier as a data- element of the input:
function QuickView(element) {
var rowId = $(element).data('id');
// here comes the rest of your code.
}
$.ajax({
url: "fetchurban.php",
method: "POST",
data:{id:id},
dataType: "JSON",
success: function(data){
if (data){
var trHTML = '';
$.each(data, function (i, item) {
trHTML +='<tr><td><input type="checkbox" data-id="'+ item.TblID +'" onclick="QuickView(this)"></td><td>' + item.Type + '</td><td>' + item.Master + '</td><td>' + item.Slave + '</td><td>' + item.Orbit + '</td><td>' + item.Mode + '</td><td><span class="glyphicon glyphicon-download"> </span><span class="glyphicon glyphicon-cloud-download"></span></td></tr>' ;
});
$('#ftbl tbody').append(trHTML);
}
}
})
})
Here's a demo of the above.
EDIT:
I removed the initial sentence regarding not being allowed to use an integer for the ID attribute as it is no longer valid as Quentin pointed out in the comments. It's sometimes hard to forget what you once learned.

Json data on view not working MVC

Controller: In my controller I am getting data from sap b1if service.
I want to get json data from controller to view.
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient B1ifSerPro
= new ServiceReference1.ipostep_vP001sap0003in_WCSX_comsapb1ivplatformruntime_INB_WS_CALL_SYNC_XPT_INB_WS_CALL_SYNC_XPTipo_procClient();
ServiceReference1.SelectQueryType request = new ServiceReference1.SelectQueryType();
request.Query = "Select TOP 1000 r.U_JobNr as U_JobNr,r.Code as Code,r.U_HlSQty as U_HlSQty,r.U_JobTp as U_JobTp,r.U_RDate as U_RDate,r.U_RTime as U_RTime,r.U_ASDate as U_ASDate,r.U_ASTime as U_ASTime,r.U_AEDate as U_AEDate,r.U_Lorry as U_Lorry,r.U_Driver as U_Driver,e.U_ZpCd as U_ZpCd,e.U_City as U_City,e.U_Phone1 as U_Phone1,e.U_SiteTl as U_SiteTl,r.U_ConNum as U_ConNum,r.U_CstWgt as U_CstWgt,r.U_Price as U_Price,r.U_TCTotal as U_TCTotal,r.U_SLicCh as U_SLicCh,r.U_PayMeth as U_PayMeth,r.U_JCost as U_JCost,r.U_RTimeT as U_RTimeT,r.U_SLicNr as U_SLicNr,r.U_VehTyp as U_VehTyp,r.U_IDHRTCD as U_IDHRTCD,r.U_IDHSEQ as U_IDHSEQ,r.U_CustRef as U_CustRef,r.U_Rebate as U_Rebate,r.U_WROrd as U_WROrd,r.U_WRRow as U_WRRow,e.U_Status as U_Status,r.U_RowSta as U_RowSta,r.U_LnkPBI as U_LnkPBI,r.U_AddCost as U_AddCost,r.U_AddCharge as U_AddCharge,r.U_ValDed as U_ValDed,e.U_PCardCd as U_PCardCd,e.U_SCardCd as U_SCardCd,r.U_OrdTot as U_OrdTot,r.U_PCTotal as U_PCTotal FROM[#IDH_JOBSHD] r ,[OCRD] bp ,[#IDH_JOBENTR] e WHERE r.U_JobNr = e.Code AND (r.U_CustCd = bp.CardCode Or (r.U_CustCd = '' AND r.U_ProCd = bp.CardCode)) ";
ServiceReference1.SelectQueryResponseType Response = B1ifSerPro.ZSelectQuery(request);
Response.SelectQueryResult.ToList();
//ServiceReference1.SelectQueryResponseTypeRow row = (ServiceReference1.SelectQueryResponseTypeRow)Response.SelectQueryResult.GetValue(1);
return Json(Response.SelectQueryResult.ToList(), JsonRequestBehavior.AllowGet);
//return Json("",JsonRequestBehavior.AllowGet);
}
My view as is follow:
JS is not working in my case. I want to get data as json form Controller and render in HTML using Bootstrap or simple will work.
#Model IEnumerable<BusinessLayer.OSM>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var osmlist;
$.ajax({
url:'#Url.Action("Index", "OSM")' , // '/OSM/Index/',
type: 'Get',
Data:{},
cache: false,
async: false,
DataType: 'Json',
success: function (data) {
osmlist = data;
var row = '';
$.each(data, function (i, item) {
row += "<tr>"
row += "<td>" + item.Code + "<td>"
row += "<td>" + item.U_JobNr + "<td>"
row += "<tr>"
$("#listRows tbody").html(row);
})
},
error: function (error) {
alert("Error : " + error.responseText);
}
});
});
</script>
<h2>Get OSM Rows</h2>
<table id="listRows" style="background-color: lightcoral">
#*<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Category</th>
<th>Price</th>
</tr>
</thead>*#
<tbody></tbody>
</table>
<hr />
Is it the typo error while putting the question here or you have forgotten to correctly close the tr and td tags in the javascript.

Not able to Bind HTML DataTable in asp.net with Java script

The HTML Code :
<div class="" style='overflow: scroll; overflow-y: hidden;'>
<table id="datatable" class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Customer Type</th>
<th>First Name</th>
<th>Last Name</th>
<th>Mobile1</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-list-data">
</tbody>
</table>
</div>
The Java Script Code:
$.ajax({
dataType: "json",
type: "POST",
url: 'http://localhost:52235/api/AdminPanel/GetCustomer',
data: data,
async: true,
success: function (data) {
var trHTML = '';
$.each(data.response.customers, function (i, item) {
trHTML += '<tr><td>' + item.customerID + '</td><td>' + item.companyname + '</td><td>' + item.customertypelovid + '</td><td>' + item.firstname + '</td><td>' + item.lastname + '</td><td>' + item.mobile1 + '</td><td>' +
'<i class="fa fa-pencil"></i>Edit<br /> <i class="fa fa-trash-o"></i>Delete' + '</td></tr>';
});
$('#datatable').append(trHTML);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
I am Getting like this as output it is displaying the data but it is not binding the data to data-table please help regarding the binding of the data-table.
There are several ways to work with this tool after getting the data from the server:
You can go through each row and populate the table by your self like you do , or you can let datatables do it for you.
I recommend you to follow this datatables tutorial.
I suggest you to follow the tutorial because if you won't you will have to use the datatables api for almost every action.
For example ,your delete action will have to use the row remove api, just deleting the row from the DOM without using the api won't update the table and will cause errors while Sorting/Searching..
This is a demo with your problem
And this is WORKING DEMO
*Notice that you first populate your table and only after that convert it to DataTable.
For your code, just add after you finished to append the rows to the table:
$('#datatable tbody').append(trHTML);
$('#datatable').DataTable();
The problem in your code is that you are just appending html rows to an initialized datatable.
You need to tell the control to bind data e.g. coming from your controller.
https://code.msdn.microsoft.com/jQuery-Datatable-With-b4f844e3#content is an example to get you startet.
Give it a try, this should fit your needs.
Did you try like this..
$.ajax({
dataType: "json",
type: "POST",
url: 'http://localhost:52235/api/AdminPanel/GetCustomer',
data: data,
async: true,
success: function (data) {
var trHTML = '';
$.each(data.response.customers, function (i, item) {
trHTML += '<tr><td>' + item.customerID + '</td><td>' + item.companyname + '</td><td>' + item.customertypelovid + '</td><td>' + item.firstname + '</td><td>' + item.lastname + '</td><td>' + item.mobile1 + '</td><td>' + '<i class="fa fa-pencil"></i>Edit<br /> <i class="fa fa-trash-o"></i>Delete' + '</td></tr>';
});
$('#table-list-data').html(trHTML);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});

AJAX couldn't remove the DOM data

I have a dropdown selection where the user can select a name and related data will be loaded with the selection. Everything works fine except it always keeps the first data after the second or third selection. How do I remove the first selected data's when I am selecting a value the second time?
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Course Code</td>
<td>Name</td>
<td>Grade</td>
</tr>
</thead>
</table>
<script type="text/javascript">
$('#student').on('change', function(e) {
$('#example tr:last').remove().end();
var std_id = $('#student option:selected').attr('value');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{url('ajax-student-result')}}",
data: {
std_id: std_id
},
success: function(data) {
$.each(data, function(index, subcatObj) {
$('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
});
}
});
});
</script>
I guess you are using Symfony and Twig.
I think a CSRF token is to be used only once so if you don't renew your csrf token for each ajax post request it may be the reason why it works only once.
Edit : Found this question which might help you :
Generate new CSRF token without reloading the entire form
Change the code to include removal:
success: function(data) {
$('#example tr:last')remove();
$.each(data, function(index, subcatObj) {
$('#example tr:last').after('<tr><td id="code">' + subcatObj.c_code + '</td><td id="course_name">' + subcatObj.c_name + '</td><td id="grade">' + subcatObj.grade + '</td></tr>');
});
}

Get a button working in a table From JSON Href

<table class="pull-left table table-fill">
<thead>
<tr>
<th class="table-hover">Name</th>
<th class="table-hover">Price</th>
</tr>
</thead>
</table>
</body>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].EventsUK.text;
var href = json.results.collection1[i].EventsUK.href;
$("table").append("<tbody><tr><td>"+title+"</td><td>"+href+"</td></tr></tbody>");
}
},
error: function(error){
console.log(error);
}
});
</script>
I receive the href from the website. How would i get the href into a button link? To display in the same place (the table. I have tried adding all the button commands i could to the code which hasnt worked, I have also tried adding it infront he of href and infront of the plus symbols.
Sam
Links are not resolved by themselves in HTML. You need to use the <a> tag instead. It's very dirty, but the quickest trick to do that, given your code, is changing your append into
$("table").append(""
+ "<tbody>"
+ "<tr>"
+ "<td>" + title + "</td>"
+ "<td>" + href + "</td>"
+ "</td>"
+ "</tr>"
+ "</tbody>"
);
... though I don't get the meaning of the table.

Categories

Resources