jQuery: Repeating Records using for loop array.length - javascript

I think I am getting a logic problem using jQuery to fetch record from a service API with AJAX and using following piece of code.
There is no error but this code is repeating records in HTML table (Drafts) -
like twice.
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft += "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}

Here you go with a solution
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
$("#Drafts").append(`<tr>
<td>${data.TableDrafts[i].nMBM}</td>
<td>${data.TableDrafts[i].nMTM}</td>
<td>${data.TableDrafts[i].sType}</td>
</tr>`);
}
}
}
Mistake was, you are adding the new tr in the variable as well as appending the variable content.
Or else you can do
success: function (data) {
if (data) {
console.log(data);
var textDraft = "";
for (var i = 0; i < data.TableDrafts.length; i++) {
textDraft = "<tr><td>" + data.TableDrafts[i].nMBM + "</td><td>" + data.TableDrafts[i].nMTM + "</td><td>" + data.TableDrafts[i].sType + "</td></tr>";
$("#Drafts").append(textDraft);
}
}
}
Hope this will help you.

Related

facing issues while Displaying Json data in to dynamic tabs using Javascript

I am trying following code to display the tabs and tab content from Json data dynamically
<script>
var area, cus, project, curst;
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function(responseText) {
console.log("rs" + responseText.toString());
var jsonData = JSON.parse(responseText);
var questions = new Array();
for (var i = 0; i < jsonData.length; i++) {
area = jsonData[i].area;
console.log("area" + area);
project = jsonData[i].projectName;
console.log("poj" + project);
projectdes = jsonData[i].projectDescription;
console.log("pojdes" + projectdes);
curst = jsonData[i].currentStatus;
console.log("cus" + curst);
var test = {
area: area,
cus: curst,
project: project,
projectdes: projectdes,
}
questions.push(test);
console.log("output" + test);
alert(JSON.stringify(test));
}
}
});
for (var i in test) {
$('.nav-tabs').append('<li role="area" class="">' + i + '</li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < data[i].length; j++) {
var obj = data[i][j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.tab-content').append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
</script>
<body>
<div class="container">
<ul class="nav nav-tabs" role="tablist"></ul>
<div class="tab-content"></div>
</div>
</body>
My Json data is coming correctly in JSON format from DB: Below data is coming fine from DB . I printed using alert statement
{"area":"CSE","cus":"progress","project":"Project 1","projectdes":"Class 1st"}
{"area":"ECE","cus":"complered","project":"Project 2","projectdes":"This is class 1st Project"}
{"area":"IT","cus":"progress","project":"project 1","projectdes":"This is Class 2nd project"}
{"area":"IT","cus":"pending","project":"Project 2","projectdes":"This is class 2nd project"}
I am trying to display area in tabs and other fields in tab content.But
the data is not getting displayed in jsp. I tried so many ways.But still data is not getting in tabs and tabs content. Please let me know where I am going wrong.
I updated the answer, you can replace the part of your <script> tag by the code below. And to make the UI feel better, modify the HTML and DOM part as per the UI frameworks like bootstrap, etc.
<script>
$.ajax({
type: "POST",
url: "./QuizServlet",
success: function (responseText) {
var jsonData = JSON.parse(responseText);
var uniueTabs = getUniqueLists(jsonData);
for (var i = 0; i < uniueTabs.length; i++) {
$('.nav-tabs').append('<li role="area" class="my-li' + i + '"><a href="#' + i +
'" aria-controls="' + i + '" role="tab" data-toggle="tab">' + uniueTabs[i].area +
'</a></li>');
var div = '<div role="tabpanel" class="tab-pane" area="' + i + '">';
for (var j = 0; j < uniueTabs[i].tabContent.length; j++) {
var obj = uniueTabs[i].tabContent[j];
div += '<div area="' + obj.project + '">' + obj.projectdes + '</div>';
}
$('.my-li' + i).append(div);
}
$('.nav-tabs li').eq(0).addClass('active');
$('.tab-content div').eq(0).addClass('active');
}
});
function getUniqueLists(responseText) {
var resArr = [];
responseText.filter(function (x, i) {
if (resArr.indexOf(x.area) === -1) {
resArr.push(x.area);
}
})
//console.log(resArr);
return mergeDataAreaWise(resArr, responseText);
}
function mergeDataAreaWise(area, responseText) {
var tabList = [];
for (var i = 0; i < area.length; i++) {
tabList.push({
area: area[i],
tabContent: []
});
}
for (var i = 0; i < tabList.length; i++) {
for (var j = 0; j < responseText.length; j++) {
var Obj = {
cus: responseText[j].cus,
project: responseText[j].project,
projectdes: responseText[j].projectdes
}
var currentArea = responseText[j].area;
if (tabList[i].area === currentArea) {
tabList[i].tabContent.push(Obj);
}
}
}
console.log(tabList);
return tabList;
}
</script>
Here is a similar plunkr example

Javascript Sort Error with sort function possible simple fix

Probably a simple fix, The rest of the table is sorted excpet this part here
(right at the top)
The table will work now and again in the right order (data from source does not change) but is really dicey when it does or not
Ideas?
Sam
Heres the code
//first define a function
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(3)").text().trim();
var dataB = $(b).find("td:eq(3)").text().trim();
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url1',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tr ><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'url2',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button =
"<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>" + section +
"</td><td>" + no + "</td><td>" + price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
The sorting as to do with spaces but is also linked to your jquery selector.
As often, array are 0 index based in Jquery, then if you want to sort on your price your 2nd column (0-index based) you need to do as below :
var sortTable = function() {
$("#tableid tbody tr").detach().sort(function(a, b) {
var dataA = $(a).find("td:eq(2)").text().replace(/\s/g, "");
var dataB = $(b).find("td:eq(2)").text().replace(/\s/g, "");
return parseFloat(dataA.substring(1)) - parseFloat(dataB.substring(
1));
}).appendTo('#tableid');
};
var json = {results:[{price:"$12 .45"}, {price:"$13 .45"}, {price:"$12 .05"}, ]}
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
$("#tableid").append("<tr ><td>section</td><td>no</td><td>" + price);
}
sortTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableid"></table>
`

Javascript error with sort

i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}

Jquery + $.each + dynamic operation + using parameters

function Controles(contro, nomtab, numtab, action, nomcla, tipdat, lista, datos) {
$(document).on('click', '.'+contro+' #IZQTOD', function(event) {
$.getJSON(action+'&rows='+rows+'&page=1', function(datos) {
var nuevafila;
$.each(datos+tipdat, function(index, data) {
nuevafila = nuevafila + "<tr class='Fila-Grid-"+nomcla+"' id='" + numtab + (index + 1) + "'>";
nuevafila = nuevafila + "<td class='Columna1'>" + (index + 1) + "</td>";
var list = lista.split("-");
for (var j = 1; j < list.length; j++) {
nuevafila = nuevafila + "<td class='Borde-'>" + data+list[j] + "</td>";
}
nuevafila = nuevafila + "</tr>";
});
$('#'+nomtab+' tr:eq(1)').after(nuevafila);
});
});
}
I want to run this piece of code as a function of javascript in order to reuse code.
The part that does not work for me is the part of each:
   $. each (+ tipdat data, function (index, data) {
Where "datos" is an object with variables (set and get) (codcli, name, apepat)
I mean to call codcli I do:
   $. each (datos.codcli, function (index, data) {
}
But this way is static. I want to do through dynamic parameters.
So the question is how to pass parameters to successfully achieve? Or is that you can not do? There will always be static?
in the code above what I want to do is, but obviously does not work:
tipdat=".codcli"
   $. each (datos+tipdat, function (index, data) {
}
I think you're looking for bracket notation.
var tipdat = "codcli";
$.each(datos[tipdat], function (index, data) {
//...
});
Is the same as:
$.each(datos.codcli, ...
If your string has multiple properties, I would do something like this:
var tipdat = "codcli.cod";
var objToIterate = datos;
var parts = tipdate.split('.');
for(var i = 0; i< parts.length; i++) {
objToIterate = objToIterate[parts[i]];
}
$.each(objToIterate, function (index, data) {
//...
});

Data fetched from JSON not getting updated

Below is the script:
$(document).ready(function () {
$.getJSON('table.json', function (data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
});
});
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000);
});
}
I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert. But data is not getting updated. Please tell me what I am doing wrong.
getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.
Also look at your code, you are never processing the data
var poll = function () {
alert("poll");
$.getJSON('dummy.json', function (data) {
setTimeout(poll, 5000); //<--where is the processing you do nothing with the response???
});
}
$(document).ready(function() {
// make the initial JSON request
$.getJSON('table.json', init)
});
function poll() {
// make the subsequent JSON requests
$.getJSON('dummy.json', update);
}
function init(data) {
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i = 0, size = data.length; i < size; i++) {
html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll, 5000);
}
function update(data) {
var rows = $("#mytable tr.tablecontent").toArray();
for (var i = 0, size = data.length; i < size; i++) {
if (rows[i])
rows[i].cells[3].firstChild.data = data[i].bid;
}
setTimeout(poll, 5000);
}
Here's the update function with more jQuery:
function update(data) {
$("#mytable tr.tablecontent > td:nth-child(4)")
.slice(0, data.length)
.text(function(i) {
return data[i].bid;
});
setTimeout(poll, 5000);
}

Categories

Resources