Issues attempting to display data from JSON file - javascript

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]

Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.

The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Related

Javascript - Fill HTML table on PDF with Woocommerce order table data

I'm developing a way to export Woocommerce order data into a PDF doc table, using javascript.
For that I'm storing the innerText values of each order table cell in different let variables and later
use those variables to populate a HTML table which will appear in my final PDF doc.
I feel like I'm close to hitting gold, but I get a console error of Uncaught TypeError: Cannot read property 'innerText' of undefined on browser.
This is my code so far, any idea why I'm getting this error and any way I could fix it?
function printData(){
let orderTableData = document.getElementsByClassName("woocommerce_order_items")[0].innerHTML;
let orderTableSize = document.getElementById("order_line_items");
let tamanho = orderTableSize.rows.length;
let orderPricesData = document.getElementsByClassName("wc-order-totals")[0].innerHTML;
let orderItemName = document.getElementById("order_line_items").getElementsByClassName("name")[0].innerText;
let orderItemPrice = document.getElementById("order_line_items").getElementsByClassName("item_cost")[0].innerText;
let orderItemQtd = document.getElementById("order_line_items").getElementsByClassName("quantity")[0].innerText;
let orderItemTotal = document.getElementById("order_line_items").getElementsByClassName("line_cost")[0].innerText;
for(var j = 0; j <= tamanho; j++){
window.frames["print_frame"].document.body.innerHTML = "<table border='1' width='100%'><tr><th>Item</th><th>Preço uni.</th><th>Qtd.</th><th>Total</th></tr><tr><td>" + document.getElementById("order_line_items").getElementsByClassName("name")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("item_cost")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("quantity")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("line_cost")[j].innerText + "</td></tr></table>";
}
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
I'll also leave a print of the Woocommerce table I'm using for test.
In your loop, you don't need to use the condition <= (less than or equal) because you are begining with 0 (because its a array index), just use < (less than) in these cases.
Another thing, You should use a iframe to put the content you want to print, I didn't understand the window.frames logic you used.
I tested that snippet and it works:
function printData(){
let orderTableData = document.getElementsByClassName("woocommerce_order_items")[0].innerHTML;
let orderTableSize = document.getElementById("order_line_items");
let tamanho = orderTableSize.rows.length;
let orderPricesData = document.getElementsByClassName("wc-order-totals")[0].innerHTML;
let orderItemName = document.getElementById("order_line_items").getElementsByClassName("name")[0].innerText;
let orderItemPrice = document.getElementById("order_line_items").getElementsByClassName("item_cost")[0].innerText;
let orderItemQtd = document.getElementById("order_line_items").getElementsByClassName("quantity")[0].innerText;
let orderItemTotal = document.getElementById("order_line_items").getElementsByClassName("line_cost")[0].innerText;
let iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
for(var j = 0; j < tamanho; j++){
iframe.contentDocument.body.innerHTML = "<table border='1' width='100%'><tr><th>Item</th><th>Preço uni.</th><th>Qtd.</th><th>Total</th></tr><tr><td>" + document.getElementById("order_line_items").getElementsByClassName("name")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("item_cost")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("quantity")[j].innerText + "</td><td>" + document.getElementById("order_line_items").getElementsByClassName("line_cost")[j].innerText + "</td></tr></table>";
}
iframe.contentWindow.focus();
iframe.contentWindow.print();
document.body.removeChild(iframe);
}

javascript - unable to populate 2D array

My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
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>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}
tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

Adding a table from database with javascript

I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.

post data from table row like json format

this is related to my last question(
NOTE: I already got some good answers there). I'm doing a program that will filter. I didn't include this question because i thought that it is easier for me to add text as long as i know how to get the data from the row. But to my dismay, I wasn't able to code a good program til now.
Im currently using this javascript code (thanks to Awea):
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
my question is: How to add text before the data from the row? like for example, this code alert
the first row like data1.1 data1.2 data1.3,
then the second row like data2.1 data2.2 data2.3,
I want my output to be displayed like this
[
{"name":"data1.1","comparison":"data1.2", "value":"data1.3"},
{"name":"data2.1","comparison":"data2.2", "value":"data2.3"},
{"name":"data3.1","comparison":"data3.2", "value":"data3.3"}
{.....and so on......}]
but before that happen, i want to check if all the FIRST cell in a row is not empty. if its empty, skip that row then proceed to next row.
is there somebody can help me, please...
Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/
Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).
// object to hold your data
function dataRow(value1,value2,value3) {
this.name = value1;
this.comparison = value2;
this.value = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
for(var i = 1; i <= $("table tr").length; i++){
// check if first field is used
if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") select[class='field']").val(),
$("table tr:nth-child(" + i + ") select[class='comp']").val(),
$("table tr:nth-child(" + i + ") input").val())
);
}
}
// consider using a JSON library to do this for you
for(var i = 0; i < dataArray.length; i++){
var output = "";
output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
alert(output);
}
})
There are two things you need to do here. First get the data into an array of objects, and secondly get the string representation.
I have not tested this, but it should give you a basic idea of what to do.
Edit Please take a look at this JS-Fiddle example I've made. http://jsfiddle.net/4Nr9m/52/
$(document).ready(function() {
var objects = new Array();
$('table tr').each(function(key, value) {
if($(this).find('td:first').not(':empty')) {
//loop over the cells
obj = {};
$(this).find('td').each(function(key, value) {
var label = $(this).parents('table').find('th')[key].innerHTML;
obj[label] = value.innerHTML;
});
objects.push(obj);
}
});
//get JSON.
var json = objects.toSource();
$('#result').append(json);
});
var a = [];
a[0] = "data1.1 data1.2 data1.3"
a[1] = "data1.6 data1.2 data1.3"
var jsonobj = {};
var c = []
for (var i = 0;i
alert(c); //it will give ["{"name":"data1.1","comp...1.2","value":"data1.3"}", "{"name":"data1.6","comp...1.2","value":"data1.3"}"]
u have to include library for function from JSON.stringify from
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
hope this helps

onclick event not firing

var subjectList;
function PageMaster()
{
this.contentDiv = document.getElementById("content");
}
/**
* Builds the main part of the web page based on the given XML document object
*
* #param {Object} xmlDoc the given XML document object
*/
PageMaster.prototype.doIt = function(xmlDoc)
{
alert("PageMaster()");
alert("Clear page...");
this.contentDiv.innerHTML = "";
if (null != xmlDoc)
{
alert("Build page...");
//create div Post
var divPost = document.createElement("div");
divPost.className = "post";
//create h1 element
var h1Element = document.createElement("h1");
var headingText = document.createTextNode("Invitations");
h1Element.appendChild(headingText);
//insert h1 element into div post
divPost.appendChild(h1Element);
subjectList = xmlDoc.getElementsByTagName("subject");
var groupList = xmlDoc.getElementsByTagName("group");
for (var i = 0; i < subjectList.length; i++) //for each subject
{
var divEntry = document.createElement("div");
divEntry.className = "entry";
var subjectNum = subjectList[i].attributes[0].nodeValue;
var subjectName = subjectList[i].attributes[1].nodeValue;
var groupId = groupList[i].attributes[0].nodeValue;
var groupName = groupList[i].attributes[1].nodeValue;
var ownerId = groupList[i].attributes[2].nodeValue;
//set up the invitation table attributes
var table = document.createElement("table");
table.width = 411;
table.border = 3;
table.borderColor = "#990000"
tableRow = table.insertRow(0);
tableCell = tableRow.insertCell(0);
var cellContent = "";
//create invitation message
var invitationMsg = "<p>Subject : " + subjectNum + " - " + subjectName + "</p>";
invitationMsg += "<p>You are invited to join " + groupName + " (groupId : " + groupId + ") by owner Id:" + ownerId + "</p>";
cellContent += invitationMsg;
//create buttons
cellContent += "<input type='button' id='acceptButton" + i + "' value='Accept' onclick='acceptInvitation(i)'>"
cellContent += "<input type='button' id='declineButton" + i + "' value='Decline'>"
tableCell.innerHTML = cellContent;
divEntry.appendChild(table);
var blankSpace = document.createElement("p");
divEntry.appendChild(blankSpace);
divPost.appendChild(divEntry);
}
//insert div post into div content
this.contentDiv.appendChild(divPost);
}
};
function acceptInvitation(i)
{
alert("hello");
//alert(subjectList[i].attributes[0].nodeValue);
}
above is extract of my javascript code. What the code do is to create a table of inviting group from the xml file with accept and decline button. when user press accept, the table will disappear and the table below will move up. For now I am only testing my accept invitation button to see if it works.But
my onclick function in the accept button does not work for some reason I don't understand. the alert in acceptInvitation() is not read. Any help will be appreciated. Thanks
What about:
cellContent += "[...] onclick='acceptInvitation("+i+")'>"
This ensures that i is evaluated with the value of the variable instead of as a literal
Try to call it like this
onclick='acceptInvitation();'
Not like this
onclick='acceptInvitation(i)'
dont know if that's what's causing your problem but your outputting onclick='acceptInvitation(i)' Im guessing you want to output acceptInvitation(value-of-i), that is acceptInvitation(" + i + ")
while perhaps not addressing the central problem,
onclick='acceptInvitation(i)'
in this case i would be undefined.
onclick='acceptInvitation("+i+")'
would solve at least one problem. Also, you're using an unusual mixture of innerHTML and DOM methods. Why not stick to the DOM methods and use attachEvent/AddEventListener?
edit: A list apart has a good article on binding of variables at http://www.alistapart.com/articles/getoutbindingsituations/
The following is a somewhat specialized example. See the article for more generalized case (or use a library like Prototype)
var click_hdlr = function() {
return function() {
return acceptInvitation.apply(this,arguments);
}
}
var acc_btn = document.createElement("input");
acc_btn.setAttribute("type","button");
acc_btn.setAttribute("id","accept");
acc_btn.setAttribute("value","Accept");
acc_btn.addEventListener("click",click_hdlr(i),false);

Categories

Resources