appending <tr> dynamically as per the database output using AJAX - javascript

I am trying to attach multiple rows dynamically ( as per the results fetched from the database) to the existing table.
my html code
<table width="100%" border="1" class="queriedResponders">
<tbody>
<tr>
<th><strong>Select</strong></th>
<th><strong>Responder Name</strong></th>
<th><strong>Responder Company</strong></th>
<th><strong>Responder Number</strong></th>
<th><strong>City</strong></th>
<th><strong>Distance(Km)</strong></th>
</tr>
</tbody>
</table>
my jQuery code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><td><input type='radio' name='assignRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tr:last').append($row);
}
console.log($row);
}
});
});
Please note :- I am getting the desired result as I have console logged the output which is a JSON object like 1 pasted below
[{"name":"mihir panchal","company":"","number":"00919664804737","city":""}]
Please guide me as to where am I making the mistake

2 things:
You are not referencing the correct element. Your table has a class of queriedResponders, and you are targeting queriedResponder
You should be append to the tbody instead of the tr
Both of those things combined results in this:
$('table.queriedResponders tbody:last').append($row);
I've simplified the response to get a working example:
var result = [{
"name": "mihir panchal",
"company": "",
"number": "00919664804737",
"city": ""
}];
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><td><input type='radio' name='assignRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponders tbody:last').append($row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" border="1" class="queriedResponders">
<tbody>
<tr>
<th><strong>Select</strong></th>
<th><strong>Responder Name</strong></th>
<th><strong>Responder Company</strong></th>
<th><strong>Responder Number</strong></th>
<th><strong>City</strong></th>
<th><strong>Distance(Km)</strong></th>
</tr>
</tbody>
</table>

You are appending the new row to the last tr while you want to append it in <tbody>
so you should replace it with
$('table.queriedResponders > tbody:last-child').append($row);
or if you want to use your last <tr> you may use .after() instead of .append() to add the new row after your last row
$('table.queriedResponders tr:last').after($row);
Solution1: Working Demo
Solution2: Working Demo

Related

Table tbody not correctly appending

My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.
This is what it showing:
I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.
$.ajax({
cache: false,
type: 'GET',
url: '#Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',
dataType: "json",
success: function(response) {
$("#tblFiles tbody").remove();
for (var i = 0; i < response.length; i++) {
console.log(response[i]['Filename']);
console.log(response[i]['FileFullPath']);
$("#tblFiles").append('<tr><td>' + response[i]['Filename'] + '</td><td>' + response[i]['FileFullPath'] + '</td></tr>');
//var tbodyFiles = "<tr><td> " + response[i]['Filename'] + "</td>" + "<td> " + response[i]['FileFullPath'] + "</td></tr>";
}
//$("#tblFiles").append(tbodyFiles);
console.log(response);
},
error: function(resp) {
console.log('error');
}
});
<table class="table table-striped" id="tblFiles">
<thead>
<tr>
<th>Filename</th>
<th>File Fullpath</th>
#*
<th>Date Added</th>*#
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Filename)
</td>
<td>
#Html.DisplayFor(modelItem => item.FileFullPath)
</td>
#*
<td>
#Html.DisplayFor(modelItem => item.DateAdded)
</td>
*#
<td>
#Html.ActionLink(" ", "Delete", new { id = item.Id }, new { #class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
Change this:
$("#tblFiles tbody").remove();
to this:
$("#tblFiles tbody tr").remove();
and then change this:
$("#tblFiles").append(...)
to this:
$('#tblFiles tbody").append(...)
Explanation:
You were removing the entire tbody element, but appending the trs to the table not the tbody.
The proposed changes will ensure that the tbody stays present and that trs are added as children to it instead of outside of it.

Call Javascript function to get resultset of sql query and print them in html table

I am using Phonegap and jquery-Mobile-1.4.5 to create a cross platform App. Since I am a Java developer , Java script is a very new concept for mine.
I am creating a simple app where I have one html table where I want to show a select query from a database table . From here I found how to send a callback to functions.
But my problem is ,
onload is not calling my showContact(resultSet) function
How can I print the resultSet in the <tbody> tag, I do not want to use javascript concatenation inside the showContact(resultSet) function.
Part of my index.html file
<table data-role="table" id="table-custom-2" onload="showContact(resultSet)" >
<thead>
<tr class="ui-bar-d">
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<!--Print the resultSet data with a for loop here-->
</tbody>
</table>
My javascript code
function showContact(resultSet){
var db= window.openDatabase("appDb","1.0","appDb",200000);
selectRow("SELECT * FROM contact;", function(resultSet) {
console.log(resultSet);
//Don't want to access the <table> from here
});
}
/** Select Row from Table **/
function selectRow(query, callBack){
var result = [];
db.transaction(function (tx) {
tx.executeSql(query, [], function(tx, rs){
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
result[i] = { id: row['id'],
name: row['name'],
number: row['number']
}
}
callBack(result);
}, errorHandler);
});
}
You can frame the data you get from DB in a table row and assign it to the table body. See following code,
You can call the function selectrow() when the page loads
<table data-role="table" id="table-custom-2">
<thead>
<tr class="ui-bar-d">
<th>Id</th>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody id="contactlist">
<!--Print the resultSet data with a for loop here-->
</tbody>
</table>
<script>
$(document).ready(function($) {
var db= window.openDatabase("appDb","1.0","appDb",200000);
selectrow();
});
function selectrow(){
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM contact", [], function(tx, rs){
var output = '';
for(var i=0; i<rs.rows.length; i++) {
var row = rs.rows.item(i)
output += '<tr><td>' + row['id'] + '</td><td>' + row['name'] + '</td><td>' + row['number'] + '</td></tr>';
}
$('#contactlist').html(output);
}, errorHandler);
});
}
</script>

Add a <tr> element to dynamic table, dynamically without a page refresh, php jquery

I am trying to add a dynamic row to the existing table on click of button, whose rows are dynamically created using output from PHP script.
I doing an ajax call to the script insert_tr.php which returns me a TR element in the same format as the existing table with the data.Data is returned appropriately
But unfortunately, the <tr> row is not being added to the table dynamically but adds only after a page refresh.
PHP file code :
<div id="v_div">
<table class="table table-bordered table-striped" >
<thead>
<th class='col-md-2'>name</th>
<th class='col-md-2'>number</th>
</thead>
<tbody>
<?php
while ($data = pg_fetch_assoc($ret)) {
echo
"<tr id=tr_".$data['sr_number'].">
<td class='td_topic' id=title:".$data['number']." >".trim($data['name'])."</td>
<td class='td_topic' id=title:".$data['number']." >".trim($data['number'])."</td>
<td class='td_topic' id=title:".$data['number']." ><button class='btn btn-info check1' type=button title='Add Entry'>Add Entry</button></td>
</tr>";
?>
</tbody>
</table>
</div>
Javascript :
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
$(this).closest("tr").after(data);
}
});
});
});
All I want to do is add the row immediately after the current TR am on ,dynamically without a page refresh, which serves the ultimate use of an ajax call.
The reference to this is not the button that was clicked.
$(this).closest("tr").after(data);
Store a reference to the row outside the Ajax call.
$(document).ready(function() {
$("#v_div").on('click', '.check1', function() {
var field_userid = $(this).parent().attr("id");
var value = $(this).text();
var row = $(this).closest("tr");
$.post('insert_tr.php', field_userid + "=" + value, function(data) {
if (data != '') {
row.after(data);
}
});
});
});

jQuery transfer data between tables via textbox input

I asked a question yesterday and that got me going on the right path, but I'm absolutely stuck again.
Outline:
I have 3 tables;
table 1 - expected data (#expected)
table 2 - expected confirmed data (#scannedExp)
table 3 - unexpected confirmed data (#scannedUnExp)
So for a example..
if I was to enter "6666" in the input box
it would reduce qty in the "#expected" table by 1 but create a column in the "#scannedExp" table with qty of 1 (with the i.e desc, cage grabbed from the #expected table).
if we was to enter '6666' this time it would delete the "#expected" row, but increase the table "#scannedExp"
if again we was to enter '6666' this time it would add a row to "#scannedUnExp" with just the code and qty (dont need the desc or cage)
and if we was to enter say "1234" it would add a row in "#scannedUnExp"
for some reason my codes not working in Jsfiddle as it works to some extent in my browser.
http://jsfiddle.net/j3psmmo3/
<body>
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Submit"/>
<P>Scanned Expected</P>
<table id = "scannedExp" > <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Scanned Un Expected</P>
<table id = "scannedUnExp" > <thead>
<tr>
<th>Code</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Data Expected</P>
<table id = "expected"> <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
<tr id="4444" >
<td>4444</td>
<th>Car Door</th>
<td>3</td>
<th>S2222</th>
</tr>
<tr id="5555" >
<td>5555</td>
<th>door handel</th>
<td>1</td>
<th>S2222</th>
</tr>
<tr id="6666" >
<td>6666</td>
<th>headlight</th>
<td>2</td>
<th>S2222</th>
</tr>
<tr id="7777">
<td>7777</td>
<th>seat</th>
<td>5</td>
<th>S2222</th>
</tr>
</tbody>
</table>
</body>
my javascript
$(window).load(function(){
$("#btnSubmit").on("click", function(){
numRows = $("#expected tr").length; //loop thought expected data
for(var i=1 ; i<numRows ; i++){
var code = $("#expected tr:nth-child(" + i + ") td:nth-child(1)").html();
var desc = $("#expected tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("#expected tr:nth-child(" + i + ") td:nth-child(3)").html();
var cage = $("#expected tr:nth-child(" + i + ") td:nth-child(4)").html();
// if code is in expected data -1 from qty col
if(code == $("#code").val()){
$("#expected tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) - 1);
//delete if last one in expected table
if(qty ==1 ){$("#" + code).remove();}
// loop thought scanned expected table
numRowsB = $("#scannedExp tr").length;
for(var ib=1 ; ib<numRows ; ib++){
var codeExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(1)").html();
var qtyExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html();
// if in scannedExp add qty by one
if(codeExp == $("#code").val()){
$("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html(parseInt(qtyExp) + 1);
return true;
}
else{ //if not found in expected table add row to scannedExp
$("#scannedExp tbody").append("<tr><td>" + $("#code").val() + "</td><td>" + desc + "</td><td>1</td><td>" + cage + "</td></tr>");
return true;
}
}
return true;
}
else{
alert("not in expected");
}
}})
});
I noticed from your fiddle that the button does not trigger the click event.
Your code had 3 problems that I have fixed and then the code worked fine.
First
I think you meant to use $(document).ready() instead of $(window).load().
Since you want to listen to events, it is better to wait until all DOM elements are loaded and the document is ready before attempting to do anything else.
But since the event trigger I am about to tell you about in my second point does not depend on the document being ready or not, it is not necessary. So I removed it.
Second:
I modified the code to use $(document).on('click','selector',function(){}); instead of $(element).on('click',function(){});
//Use this event
$(document).on('click','#btnSubmit',function(){
...
...
});
//Instead of using this
$("#btnSubmit").on("click", function(){
...
...
});
the .on() I used will work for DOM controls that have been loaded from the page, or ones that you added dynamically. That's why I rely on it all the time.
Third
You forgot a semi-colon at the last line of your code...
...
...
else{
alert("not in expected");
}
}}) // <-- This line has no semi-colon
});
You may check the modified code on this fiddle
The code works fine after the modification.

populating a bootstrap html table via jquery data

i just buil a data APIT trough Kimono -> https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m.
i would like to include it in a simple and nice bootstrap table, like this: http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html.
i just tried to insert the jquery code given by kimono
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function kimonoCallback(data) {
// do something with the data
// please make sure the scope of this function is global
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
but i didn't manage to create the table.
any advice?
you can active bootstrap table via javascript:
<table id="table">
<thead>
<tr>
<th data-field="nome" data-formatter="linkFormatter">Nome</th>
<th data-field="descrizione" data-formatter="linkFormatter">Descrizione</th>
</tr>
</thead>
</table>
<script>
function linkFormatter(value) {
return '' + value.text + '';
}
function kimonoCallback(data) {
$('#table').bootstrapTable({
data: data.results.collection1
});
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
jsFiddle: http://jsfiddle.net/wenyi/8svjf80g/33/
I have no idea what you want to display from your JSONP feed, but generally you can handle the display like so:
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Href</th>
<th>Text</th>
</tr>
</thead>
<tbody id="loadHere">
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
function kimonoCallback(data) {
// this will help you see data structure while you develop the table
console.log(data);
// then create your table
var results = data.results.collection1,
i;
for (i = 0; i < results.length; i += 1) {
$('#loadHere').append(
'<tr>' +
'<td>' + results[i].nome.href + '</td>' +
'<td>' + results[i].nome.text + '</td>' +
'<td>' +
'</table>');
}
}
$.ajax({
"url":"https://www.kimonolabs.com/api/2ewmh21u?apikey=lvafgzGqR6fOqrI0mXAbiPEmQGh7rR4m&callback=kimonoCallback",
"crossDomain":true,
"dataType":"jsonp"
});
</script>
Be sure to look at the console to see how the data is structured so you can determine which fields to populate the table with.
Well.. You need to actually make the table when kimonoCallback gets called.
See?
// do something with the data
// please make sure the scope of this function is global

Categories