My ajax script sends json objects to browser but the table is unable to load the json object.
My Ajax script:
$.ajax({
type : "POST",
url : "getLabels.jsp",
data : "mailingID=" + selectedValue, // posCodeSelected
success : function(data) {
response = $.parseJSON(data);// this statement sends data succesfully to browser
},
error : function(response) {
var responseTextObject = jQuery.parseJSON(response.responseText);
}
});
This is my bootstrap table embedded into my jsp page.
<table data-height="299" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1">
<thead>
<tr>
<th data-field="rowNumber" >ID</th>
<th data-field="firstname" >first name</th>
<th data-field="lastname" >last name</th>
<th data-field="organization" >organization</th>
<th data-field="city" >city</th>
<th data-field="state" >state</th>
</tr>
</thead>
</table>
Just to let you guys now this is my json response in browser:
{"rowNumber":1,"mailingID":3,"firstname":"Brian","lastname":"Fairhurst","organization":"Florida State University","city":"Tallahassee","state":"FL"}
You have to add a new row with the json object returned:
//you need to set id="tbl" to your table on the html
var table = document.getElementById("tbl");
var row = table.insertRow(table.rows.length); //insert a new row
// insert new cells with info
cells = [];
for(var i = 0;i < 6;i++){
cells[i] = row.insertCell(i);
}
// add the information store in json object
cells[0].innerHTML = response.rowNumber;
cells[0].innerHTML = response.firstname;
cells[0].innerHTML = response.lastname;
cells[0].innerHTML = response.organization;
cells[0].innerHTML = response.city;
cells[0].innerHTML = response.state;
The problem is that the HTML table isn't being populated with the data in response. Adding the data-url attribute to your HTML table should work.
So, instead of:
<table data-height="299" data-show-refresh="true" ...>
<thead>
...
You'll want to do:
<table data-height="299" data-show-refresh="true" data-url="response"...>
<thead>
...
Related
I have a web app, frontend using HTML5, backend using Django.
I the JavaScript part I dynamically create the table header based on user selection in the previous page. But when I tried to set the data-field attribute to load the data dynamically, it could not work. although there's no error in F12 dev tool, the data could not shown in the table (I checked in dev tool, the data-field is there but no data shown in frontend. The first fixed one , course dose shown).
<table id="thisTable" contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;"
id="bk-table"
data-toggle="table"
data-toolbar="#toolbar"
data-cookie="true"
data-cookie-id-table="materialId"
data-show-columns="true"
data-show-refresh="true"
data-show-fullscreen="true"
data-show-export="true"
data-height="650"
{# data-sticky-header="true"#}
{# data-sticky-header-offset-left="7em"#}
{# data-sticky-header-offset-right="7em"#}
data-click-to-select="true"
data-id-field="id"
data-show-footer="true"
data-url="/api/materials/"
data-query-params="queryParams"
data-remember-order="true"
data-pagination="true"
data-side-pagination="server"
data-total-field="count"
data-data-field="results">
<thead class="thead-dark" >
<tr contenteditable='true'>
<!--th data-sortable="true" >ID</th-->
<th data-field="courseCode" data-sortable="true" data-formatter="renderCourse"></th>
</tr>
</thead>
</table>
<script>
const eText_iBookStore = ['Course Code', 'Course Material Title', 'eISBN/VBID', 'iSBN']
function queryParams(params) {
params['limit'] = localStorage['Format'];
params['discipline'] = localStorage['discipline'];
params['Add_Information'] = localStorage['Add_Information'];
if (params['Add_Information'] == "eText_iBookStore")
{
//document.getElementsByTagName("th")[0].setAttribute("data-field", "id");
//document.getElementsByTagName("th")[1].setAttribute("data-field", "courseCode");
//document.getElementsByTagName("th")[3].setAttribute("data-field", "book.isbn");
for (i=0;i<eText_iBookStore.length;i++)
{
var tr = document.getElementById('thisTable').tHead.children[0],
th = document.createElement('th');
tr.appendChild(th);
}
$( "table thead tr th" ).each(function( index ) {
$( this ).text(eText_iBookStore[index]);
console.log(eText_iBookStore[index]);
console.log( index + ": " + $( this ).text() );
});
document.getElementsByTagName("th")[2].setAttribute("data-field", "book.title");
} }</script>
The data-field attribute dynamically loaded in js does not work like that added in HTML, (the former could not load data )
the code is working well and adding the attribute but you are creating unnecessary loop inside the loop of eText_iBookStore so i remove .each loop and added the array element directly
because i haven't something like your code inside my localStorage i just set a value to them and created the eText_iBookStore array
function queryParams(params) {
params['limit'] = "data"
params['discipline'] = "data"
params['Add_Information'] = "eText_iBookStore"
var eText_iBookStore = [1,2,3,4]
if (params['Add_Information'] == "eText_iBookStore") {
for (var i = 0;i < eText_iBookStore.length; i++) {
var tr = document.getElementById('thisTable').tHead.children[0],
th = document.createElement('th');
th.innerText = eText_iBookStore[i];
tr.appendChild(th);
}
document.getElementsByTagName("th")[2].setAttribute("data-field", "book.title");
}
}
queryParams({})
I have an HTML table and I want to iterate through its rows and create a collection or lets say an "array of objects".
For example:
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
</table>
I want to create a collection as below:
var trArray = [];
$('#tbPermission tr').each(function () {
var tdArray = [];
$(this).find('td').each(function () {
// I want to create the array of objects here …
tdArray.push();
});
// Final array
trArray.push(tdArray);
});
The arrays may be like below:
tdArray : {'UserID' : '1', 'UserName' : 'Test1'};
and:
trArray : [
{'UserID' : '1', 'UserName' : 'Test1'},
{'UserID' : '2', 'UserName' : 'Test2'}
]
Try this code
var trArray = [];
$('#tbPermission tr').each(function () {
var tr =$(this).text(); //get current tr's text
var tdArray = [];
$(this).find('td').each(function () {
var td = $(this).text(); //get current td's text
var items = {}; //create an empty object
items[tr] = td; // add elements to object
tdArray.push(items); //push the object to array
});
});
Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.
adding a working jsfiddle
This solution relies on adding thead and tbody elements which is a good idea anyways since it indicates to the browser that the table actually is a "data" table and not presentational.
jQuery has a .map() function. map is a basic function where you take an array and then replace the values with a the return value of a callback function - which results in a new array.
$([1,4,9]).map(function(){ return Math.sqrt(this) });
// [1, 2, 3]
.toArray converts the array like jQuery object we get into a "true array".
jQuery(function(){
var $table = $("#tbPermission");
var headers = $table.find('thead th').map(function(){
return $(this).text().replace(' ', '');
});
var rows = $table.find('tbody tr').map(function(){
var result = {};
var values = $(this).find('>td').map(function(){
return $(this).text();
});
// use the headers for keys and td values for values
for (var i = 0; i < headers.length; i++) {
result[headers[i]] = values[i];
}
// If you are using Underscore/Lodash you could replace this with
// return _.object(headers, values);
return result;
}).toArray();
// just for demo purposes
$('#test').text(JSON.stringify(rows));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbPermission">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
</tbody>
</table>
<textarea id="test"></textarea>
If you for whatever reason cannot change the HTML you could use the index of the rows to differentiate between headers and rows of data:
var headers = $table.find('tr:eq(0) th').map(function(){
return $(this).text().replace(' ', '');
});
var rows = $table.find('tr:gt(0)').map(function(){
// ...
});
I would suggest changing your html slightly.
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td class="userid">1</td>
<td class="username">Test1</td>
</tr>
</table>
Then in your javascript when you want to get all the elements as an array you could do.
var userIdArray = $('#tbPermission .userid').map(function(userid){ return $(userid).html(); }).toArray();
This will find all elements with a class userid on the table, collect just the values, and .toArray() that result to get a basic javascript array. You can then take that and manipulate it into whatever json structure you want, or you could possibly create your json object inside that map function.
Check the console, you will get an array with the desired objects
var arr = [];
$('#tbPermission tr:not(.header)').each(function() {
var that = $(this);
var id = that.find('td').eq(0).text();
var name = that.find('td').eq(1).text();
var obj = { 'userId': id , 'userName': name };
arr.push(obj);
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tbPermission">
<tr class="header">
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td>1</td>
<td>Test1</td>
</tr>
<tr>
<td>2</td>
<td>Test2</td>
</tr>
</table>
It's a bit tricky based on the given structure. You may have to modify the HTML a bit to map cells to headers, like below.
var myArray = [];
$("#tbPermission").find("td").each(function() {
var $this = $(this), obj = {};
obj[$this.data("column")] = $this.text();
myArray.push(obj);
});
alert ( JSON.stringify(myArray) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbPermission">
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
<tr>
<td data-column="User ID">1</td>
<td data-column="User Name">Test1</td>
</tr>
</table>
Please give in some time to learn about Array.push() and Objects in Javascript. Hope that helps.
I'm new to javascript. I'm developing a web app using javascript and HTML. Here is the code:
<html>
<body>
<table class="table table-striped table-bordered bootstrap-datatable datatable responsive">
<thead>
<tr>
<th>No:</th>
<th>Username</th>
<th>Date registered</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="result11" >
<script type="text/javascript">
Parse.initialize("keyyyyyy", "idddddddddddddddddddddd");
var GameScore = Parse.Object.extend("doctor_details");
var query = new Parse.Query(GameScore);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var docname = object.get('doc_name');
var date = object.get('doc_regdate');
var k = i + 1;
document.getElementById('result11').innerHTML +="<tr ><td>"+k+"</td><td>"+docname+"</td><td>"+date+"</td><td>doctor</td><td><a class='btn btn-info' href='edit-doctor.php'><i class='glyphicon glyphicon-edit icon-white'></i>Edit</a></td></tr>";
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
</tbody>
</table>
</body>
</html>
The problem is that I fetch data from parse using javascript parse sdk and render the data to the "tbody" of the data table using inner HTML. Here I get data table showing "no data".Dynamic data displaying only after the data table is displayed.
Pagination,search nothing is working.
I need to know how can I render data when the data table loads.Thanks in advance.
I am trying to filter the rows of a table to display the results of entered text in the search bar. The code below does the job but for some reason filters the column headings as well.
$('#search').keyup(function () {
var data = this.value.split(" ");
var rows = $(".Info").find("tr").hide();
if(this.value ==""){
rows.show();
return;
}
rows.hide();
rows.filter(function(i,v){
var t = $(this);
for (var d = 0; d < data.length; d++) {
if (t.is(":Contains('" + data[d] + "')")) {
return true;
}
}
return false;
}).show();
});
HTML
<input type = "search" name = "search" id = "search">
<table style ="width:95%" class = "Info">
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
</table>
The user adds rows which is why i haven't written any HTML for it.
Any help would be appreciated. Thanks in advance
http://jsfiddle.net/szjhngwm/
It looks like you need to filter using tbody
<table style ="width:95%" class = "Info">
<thead>
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
<thead>
<tbody>
</tbody>
</table>
var rows = $(".Info tbody tr").hide();
Another way to do this would be to use jQuery's :gt() selector.
The only thing that would change is this line:
var rows = $(".Info").find("tr:gt(0)").hide();
Notice the addition of :gt(0) to your tr.
In this example:
function onRowClickHandler(evt){
var clickedTaxLotId = grid.getItem(evt.rowIndex).PARCELID;
var selectedTaxLot;
dojo.forEach(map.graphics.graphics,function(graphic){
if((graphic.attributes) && graphic.attributes.PARCELID === clickedTaxLotId){
selectedTaxLot = graphic;
return;
}
});
var taxLotExtent = selectedTaxLot.geometry.getExtent();
map.setExtent(taxLotExtent);
}
And they select the PARCELID from here:
<th field="PARCELID">Parcel ID</th>
<th field="OWNERNME1" >Owner 1</th>
<th field="OWNERNME2">Owner 2</th>
<th field="RESYRBLT ">Year Built</th>
<th field="SITEADDRESS" width="100%">Address</th>
But now my problem is that i have a <th field="1"> that isnt changeable. But i need to get that value like this var clickedTaxLotId = grid.getItem(evt.rowIndex).2; but in javascript that isnt possible.
table header looks like this:
<div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'bottom'" style="height:350px;" >
<table data-dojo-type="dojox.grid.DataGrid" jsid="grid" id="grid" data-dojo-props="rowsPerPage:'5', rowSelector:'20px'">
<thead>
<tr>
<th field="0" width="auto" >
Gezocht op
</th>
<th field="1" width="auto" >
Gevonden
</th>
</tr>
</thead>
</table>
EDIT
Here i set the value of the th field. This gets done by dataForGrid. the first field is "0" and gets filled with result.foundFieldName, "1" with result.value
map.graphics.clear();
var dataForGrid = [];
//Build an array of attribute information and add each found graphic to the map
dojo.forEach(results, function(result) {
var graphic = result.feature;
dataForGrid.push([result.foundFieldName, result.value]);
var userlabel = result.value;
switch (graphic.geometry.type) {
case "point":
graphic.setSymbol(markerSymbol);
break;
case "polyline":
graphic.setSymbol(lineSymbol);
break;
case "polygon":
graphic.setSymbol(polygonSymbol);
break;
}
map.graphics.add(graphic);
});
var data = {
items: dataForGrid
};
var store = new dojo.data.ItemFileReadStore({
data: data
});
grid.setStore(store);
}