logic issue with spitting out data, variables being repeated - javascript

I am trying to parse out a table that has customers vertically and time stamps horizontally. what I have so far does this but repeats the time stamps from previous customers with each loop. Here is my code:
json = JSON.parse(xmlHTTP.responseText);
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++)
{
message = message + "<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++)
{
eventmsg = eventmsg + "<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message = message + eventmsg + "</tr>";
}
message = message + "</table>";
The JSON looks like this:
- collection: [
- {
- customer: {
id: "1",
name: "Mr Jones",
customer_id: "1"
}
-events: [
-{
event_id: "1",
time_stamp: "1377083342"
}
-{
event_id: "2",
time_stamp: "1377083342"
}

I see no errors here try this .. if it does not work past part of the json.
var json = JSON.parse(xmlHTTP.responseText),
message = "<table><tr id='head_table'><td>Name:</td><td>Rnd 1:</td><td>Rnd 2:</td><td>Rnd 3:</td><td>Rnd 4:</td><td>Rnd 5:</td><td>Rnd 6:</td><td>Options:</td></tr>";
for(var i=0; i<json.collection.length; i++){
message+="<tr><td>" + json.collection[i].customer.name + "</td>";
for(var j=0; j<json.collection[i].events.length; j++){
message+="<td>" + json.collection[i].events[j].time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";
you don't need to write msg=msg+evntmsg it's confusing and leads to errors
also you don't need another var for events one is enough as you just append
so msg+=newstring
think o it as you just append a string.
tip.: cache your json.
var collection = JSON.parse(xmlHTTP.responseText).collection
for(var i=0 , co ; co = collection[i] ; ++i){
message+="<tr><td>" + co.customer.name + "</td>";
for(var j=0 , ev ; ev = co.events[j] ; ++j){
message+="<td>" + ev.time_stamp + "</td>";
}
message+="</tr>";
}
message+="</table>";

Related

ajax response can not be displayed

This is my javascript function that pull the data from the following link
function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var tr = "<tr>";
var td1 = "<td>" + data[i]["id"] + "</td>";
var td2 = "<td>" + data[i]["fno"] + "</td>";
var td3 = "<td>" + data[i]["attn_no"] + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3);
}
console.log(data);
});
}
This is the output of this function in console.I want to display this output in html table and also want to send to server using datatable
In this response I want to display array data in html table and also want to send this array data to server
{status: 1, data: Array(4)}
data:Array(4)
0:{id: "1", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
1:{id: "2", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
2:{id: "3", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"}
3:{id: "4", fno: "16078134", hostel_id: "12345", attn_no: "0010146998", create_date: "2017-08-21 10:31:02"
function jsonCall1() {
$.post("http://tallentex.com/phpwebservices/feedbackapp/index.php/hostel_service/syncData", { id: 0 }, function (data) {
var tbl=$("<table/>").attr("id","mytable");
$("#dv").append(tbl);
for (var i = 0; i < data.length; i++) {
var str = `<tr>
<td>${data[i].id}</td>
<td>${data[i].fno}</td>
<td>${data[i].attn_no}</td>
</tr>`;
$("#mytable").append(str);
}
console.log(data);
});
}

How to create a table in JS

I need to create a table in JS and show it in the page but it does not seem to work. I have two functions, the first one to actually create the table and the second one to order the elements in the table. I tried creating a simple div in html with id showlist but the table does not appear in the page. Please see the code below.
function myfunction() {
var array2 = [];
var list = "<table border ='1'>";
array2.sort(order);
list = list + "<tr>";
list = list + "<td colspan = '2'> TABLE </td>";
list = list + "</tr>";
list = list + "<tr>";
list = list + "<td> PRICE</td>";
list = list + "</tr>";
for (i = 0; i <= array2.length; i++) {
list = list + "<tr>";
list = list + "<td>" + array2[i].name + "</td>";
list = list + "<td>" + array2[i].price + "</td>";
list = list + "</tr>";
}
list = list + "</table>";
$("#showlist").html(list);
}
function order(n1, n2) {
if (n1.price > n2.price) {
return 1;
} else {
if (n1.price < n2.price) {
return -1;
} else {
return 0;
}
}
}
Your for loop <= runs from 0 to array2.length, it should be < - from 0 to array2.length-1.
for (i = 0; i < array2.length; i++) {
// ^_ Notice change here
...
}
Else, the last iteration would throw undefined errors.
Uncaught TypeError: Cannot read property 'name' of undefined
Fiddle Example

Array.sort not working correctly

I need the sort function to sort the dates from the earliest date to the latest date. What can I do to fix this in my tasks table?
var tasks = new Array();
var index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
//add array and populate from tempdate and temptask
//generate html table from 2d javascript array
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a,b){return new Date(b.Date).getTime() - new Date(a.Date).getTime()});
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
I have tried many different syntax variations and can not get the sort function to sort in descending order
Since the date is represented as
the number of milliseconds since 1 January, 1970 UTC (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
the sorting order you are looking for is ascending not descending.
Also, as #birdspider already commented, there is no use of creating new Date objects and invoking the getTime() method. They are comparable as they are.
To summarize the above points, try using the following sorting function:
function sortDatesAsc(tempdateA, tempdateB) {
return tempdateA - tempdateB < 0 ? -1 : (tempdateA > tempdateB ? 1 : 0);
}
tasks.sort(sortDatesAsc);
You're subtracting a.Date from b.Date, exactly the reverse of what you want.
Flip those around (and remove the unnecessary new Date() wrappers, although they're not actually breaking anything) and you'll get the correct sort:
var tasks = [],
index = 0;
function addTask() {
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);
tasks[index] = {
Date: tempdate,
Task: temptask,
};
index++
tasks.sort(function(a, b) {
return a.Date.getTime() - b.Date.getTime()
});
var tablecode = "<table class='tasktable'>" +
"<tr>" +
"<th>Date</th>" +
"<th>Task</th>" +
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode += "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode += "</table>";
document.getElementById("bottomright").innerHTML = tablecode;
return false;
}
document.getElementById('add').addEventListener('click', addTask);
<p>Task:
<input type="text" id="taskinfo" /></p>
<p>Date:
<input type="date" id="taskdate" /></p>
<button id="add">add</button>
<div id="bottomright"></div>

create table with values using js

I want to create table using javascript and fill it with data. So I decided to use prompt method and loop while.
But when I try to load page I always get two error message in google chrome developer tools
Here is the code
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function onStart() {
var list = new Array();
var headers = new Array("Имя","Отчество","Фамилия","Дата рождения");
var i = -1;
while(true) {
var a = prompt("Имя","noname");
var b = prompt("Отчество","nomiddlename");
var c = prompt("Фамилия","nosurname");
var d = prompt("Дата рождения!",0);
if (confirm("Уверены что хотите добавить студента?")) {
i++;
list[i] = a + "-" + b + "-" + c + "-" + d;
}else{ break; };
}
tab = "<table>";
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
tab +="</table>";
document.write(tab);
};
</script>
</head>
<body onLoad = "onStart()">
</body>
What's the problem?
Your for loops seem to be mis-indented and not closed properly
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Should be
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
for(var j = 0; j < list.length; j++) {
var params = list[i].split('-');
tab += "<tr>";
for(k = 0; k < params.length;k++) {
tab +="<td>" + params[k] + "</td>";
}
tab +="</tr>";
}
Not directly related to your question, but you have a few other common javascript errors.
By not declaring variables with var, you are unintentionally creating global variables. While this probably isn't a huge issue on your page, but it is bad practice.
In addition, you should wrap your <th> tags you are appending inside of a <tr>, as the only "valid" element within a <table> is a <tr> (technically its tbody, thead, and tfoot, of which the only valid children is <tr>).
You're missing the closing } on your first loop:
for(j = 0; j<headers.length;j++) {
tab += "<th>" + headers[j] + "</th>";
}
I would go to guess he is trying to loop thru headers, followed by columns, then close the table. Not loop thru headers, and for each header add all rows. And, certainly not loop thru headers and for each header loop through all rows and close and write the table.
In your code onStart(){} method is not closed properly. Add one more "}" in front of the below code
</script>
</head>

Tweak needed to store multiple data in Javascript array or an object

I have a string as
var str = 'Supplier Name^supplier^left^string*Spend (USD MM)^spend^right^number^5';
I write a function in javascript to retrieve the datafield names from the above string and store it in an array as :
function getColNamesfromConfig(str) {
var cols = new Array();
for (i = 0; i <= str.split('*').length - 1; i++) {
cols[i] = str.split('*')[i].split('^')[1];
//Will write logic to retrieve the Supplier Name, Spend (USD MM) fields etc
}
return cols;
}
The result i get is as :
cols[0] = supplier;
cols[1] = spend; and so on..(which are datafields)
Then i make a dynamic table and use the above info retrieved as :
"onResultHttpService": function (result, properties) {
var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
var colNames = getColNamesfromConfig(properties.PodAttributes.DGConfig);
var htmlMarkup = '';
htmlMarkup = "";
htmlMarkup = htmlMarkup + "<table width='100%' border='1' cellspacing='0' cellpadding='0' class='gridView gridMouseOverEffect'>";
htmlMarkup = htmlMarkup + "<tr>";
for (var c = 0, colLen = colNames.length; c < colLen; c++) {
//COLUMN LOOP (here i want to bind 'Supplier Name' and not 'supplier' which is what i get from getColNamesfromConfig(str);
htmlMarkup = htmlMarkup + "<th align='left' class='secondaryLink tableContentRow'> <h5>" + colNames[c] + "</h5>";
htmlMarkup = htmlMarkup + "</th>";
}
htmlMarkup = htmlMarkup + "</tr>";
for (var i = 0, rowlen = json_str.length; i < rowlen; i++) {
htmlMarkup = htmlMarkup + " <tr>"
for (var c = 0, colLen = colNames.length; c < colLen; c++) {
htmlMarkup = htmlMarkup + " <td align='left' class='secondaryLink tableContentRow'> " + json_str[i][colNames[c]];
htmlMarkup = htmlMarkup + "</td>"
}
htmlMarkup = htmlMarkup + "</tr>"
}
htmlMarkup = htmlMarkup + "</table>"
divPortletId = '#' + properties.id;
$(htmlMarkup).appendTo($(divPortletId));
}
If i had to retrieve the Display Name as well from the sample string how would i store it in the same array and access it?. For ex: i want something where i can just loop and get my Display Name (Supplier Name) and also datafield name (supplier). I just want to bind the Display name in my COLUMN LOOP where it is currently binding the column data field. Thus please help me TWEAK my getColNamesfromConfig(str) function to return both the datafield as well as displayname in an array or an object literal if possible..I need something like
cols[0].DisplayName = "Supplier Name";
cols[0].DatafieldName = "supplier";
cols[1].DisplayName = "Spend (USD MM)";
cols[1].DatafieldName = "spend";
function getColNamesfromConfig(str) {
var cols = new Array();
for (i = 0; i <= str.split('*').length - 1; i++) {
cols[i] = {}
cols[i].DatafieldName = str.split('*')[i].split('^')[1];
cols[i].DisplayField = str.split('*')[i].split('^')[0];
}
return cols;
}
That should do the trick

Categories

Resources