Adding a table from database with javascript - 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.

Related

Razor JQuery Populate Drop Down from Model array

I am using a WebGrid to allow CRUD on my database (using MVC and EF entities). The grid works and filters they way I want it to. There are two columns that use dropdowns to display a value tied to another table (Projects and People) and these both work well for edits/ updates. I am using JQuery for an add new row and want the new row to have select fields like the grid does (so that the user can just find the person by name instead of having to enter the ID for example). I am referencing this post from another similar question, but when I implement the code I get a syntax error that I'm having trouble understanding.
Here is my scripting on the view side that shows my failed attempt. I'm creating an array from the project repository (Text is the name of the project and Value is the ID field), and populating it with the model values: Model.Projects, and then in the add row function I want to loop through the array to add in the options.
<script type="text/javascript">
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
#:ProjectArray.push(Text: "#proj.Text", Value: "#proj.Value");
}
</script>
<script type="text/javascript">
$(function ()
{
$('body').on("click", ".add", function () {
var SelectedProject = "#Model.ProjectID";
var newRow = $('.save').length;
console.log('newRow = ' + newRow);
if (newRow == 0) {
var index = "new"+$("#meetingList tbody tr").length + 1;
var ProjectID = "ProjectID_" + index;
var Date = "Date_" + index;
var Attendees = "Attendees_" + index;
var Phase = "Phase_" + index;
var PeopleID = "PeopleID_" + index;
var Save = "Save _" + index;
var Cancel = "Cancel_" + index;
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
#* This is where I use the array to add the options to the select box*#
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
});
---remaining script omitted----
'<td><span> <input id="' + PeopleID + '" type="text" /></span></td>' +
'<td><span> <input id="' + Date + '" type="date" /></span></td>' +
'<td><span> <input id="' + Attendees + '" type="text" /></span></td>' +
'<td><span> <input id="' + Phase + '" type="text" /></span></td>' +
'<td> SaveCancel</td>' +
'</tr>';
console.log(tr);
$("#meetingList tbody").append(tr);
}
});
I am not sure how to parse the error, but the page source looks like this when creating my client side array:
var ProjectArray = new Array();
ProjectArray.push(Text: "Select Project", Value: ""); //<-- ERROR HERE:
ProjectArray.push(Text: "010111.00", Value: "74");
ProjectArray.push(Text: "013138.00", Value: "2");
So the model getting into the client side works (the text and value pairs are correct), but the error I get is for the first array.push line: missing ) after the argument list. I have played with moving this code block around, putting it in a separate <script> tag and the error likewise follows it around, always on the first array.push line. And regardless of where it is, the rest of my script functions no longer work. I think it must be something silly but I just am not seeing what I'm doing wrong.
The option list does not populate into something I can ever see, it just renders out on the page source as the javascript loop:
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
}); //-- Unexpected token here
And with the push array in its separate script block I get a second error that the last } is an unexpected token. This is some javascripting error I'm sure. But where it is an how to do this are beyond me right now.
I'm not used to javascript, and poor syntax leads to the vague errors I was getting. The first problem was fixed by adding the { . . . } around the array values. Then I created a function to create the arrays I need for people and projects as well as a function to take an array and create the option list to clean up the view code:
function createProjectArray() {
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
if (proj.Value != "") {
#:ProjectArray.push({ Text: "#proj.Text", Value: "#proj.Value" });
}
}
return ProjectArray;
}
function createPeopleArray() {
var PeopleArray = new Array();
#foreach (var person in Model.people)
{
if (person.Value != "") {
#:PeopleArray.push({ Text: "#person.Text", Value: "#person.Value" });
}
}
return PeopleArray;
}
function SelectOptionsString(MyArray, SelectedValue) {
console.log(MyArray);
var OptionsList = "";
MyArray.forEach(item => {
if (item.Value == SelectedValue) { OptionsList += '<option
selected="selected" value="' + item.Value + '">' + item.Text + '</option>'; }
else { OptionsList += '<option value="' + item.Value + '">' + item.Text
+ '</option>'; }
})
return OptionsList;
}
Taking this approach allowed me to more easily parse the code and find the syntax errors. The Array.forEach syntax was an interesting hurdle, and this site helped me test out my syntax to eventually get it working as above.
So the server creates the javascript lines to create the array, and then I use the array to create my dropdown options list. This cleans up the add row function code nicely:
$('body').on("click",".addrow", function() {
var SelectedProject = "#Model.ProjectID";
var ProjectArray = createProjectArray();
var ProjectOptions = "";
ProjectOptions = SelectOptionsString(ProjectArray, SelectedProject);
var PeopleArray = createPeopleArray();
var PeopleOptions = "";
PeopleOptions = SelectOptionsString(PeopleArray, "");
var tr = '<tr class="alternate-row"><td><span> <select id="' +
ProjectID + '>' + ProjectOptions + '</select></span></td>' +
'<td><span> <select id="' + PeopleID + '>' + PeopleOptions +
'</select></span></td>' + '</tr>'
$("#myWebGrid tbody").append(tr);
});
And it also allows for some potential code reuse.

Issues attempting to display data from JSON file

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

JavaScript for loop not working?

I haven't really used loops before and I can't seem to figure out why my code isn't working. Was hoping for someone to help point me in the right direction.
return firebase.database().ref('Users/' + uid + "/PDR").once('value').then(function display(dataSnapshot) {
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++) {
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>' + num + '</td><td>' + dateFrom + '</td><td>' + dateTo + '</td><td>' + dbActivity + '</td></tr>'
})
}
})
Im trying to pull data from my Firebase backend and display it in a table, currently it only runs once.
Thanks for any help and advice!
Not sure what is going on in the dataSnapshot object, but first step in javascript debugging, is to add alert("Here"); in your code to see what (if anything) is being returned
//Number of times the loop should run returning a value
var number = dataSnapshot.val().Total;
var i;
for (i = 1; i < number; i++){
alert("Here " + i); //Show me the loop variable
//Each time loop runs changes Firebase reference by "1"
return firebase.database().ref('/Users/' + uid + "/PDR/" + i).once('value').then(function display(dataSnapshot) {
alert(num);
alert(dateFrom );
alert(dateTo );
var num = dataSnapshot.val().number;
var dateFrom = dataSnapshot.val().dateFrom;
var dateTo = dataSnapshot.val().dateTo;
var dbActivity = dataSnapshot.val().activity;
//Each loop adds different data to table
document.getElementById("PDRTable").innerHTML += '<tr><td>'+ num +'</td><td>'+ dateFrom + '</td><td>'+ dateTo +'</td><td>'+ dbActivity +'</td></tr>'

Javascript Slickgrid timeout

I'm using Slickgrid to display data on a html site. The user can choose a table and the columns.
The code works well, but one table contains around 30 columns and around 500000 rows. Now the script takes too long and I get a firefox javascript timeout.
I know, that i can use setTimeout(), but i don't know how to use in this function.
What can i do, to avoid the javascript timeout?
function addRow(){
for (var i=0;i<arrayRow.length;i++){
var row ='{"id": "' + i + '", ';
for (var j=0;j>arrayColumn.length;j++){
row = row + '"' + arrayColumn[j] + '" : "' + array[j]+[i] + '",'
}
row = row.substr(0,row.length-1);
row = row + '}';
data[i]=JSON.parse(row);
}
if (i==arrayRow.length){
dataView.setItems(data);
}
}
Edit1: I've updated my code, but now I get the error "too much recursion".
i=0;
function addRow(){
if (i<arrayRow.length){
var row ='{"id": "' + i + '", ';
for (var j=0;j>arrayColumn.length;j++){
row = row + '"' + arrayColumn[j] + '" : "' + array[j]+[i] + '",'
}
row = row.substr(0,row.length-1);
row = row + '}';
data[i]=JSON.parse(row);
i++;
if(i%100000==0){
setTimeout(addRow,0);
} else {
addRow();
}
}
if (i==arrayRow.length){
dataView.setItems(data);
}
}
The timeout for script execution measure the time that took the execution of one method.
You need to separete "for" loop into several loops. For example you can make a method that add 100000 rows and call it with settimeout 5 times
Maybe it should be something like that:
var iFirstRow = 0;
funtion AddRows( _iFirstRow, _nRowsToAdd )
{
..implementation of adding nRows
iFirstRow = iFirstRow + nRowsToAdd;
if ( There is rows to add )
{
Call AddRows via timeout
}
else
{
..its ready
}
}

How to add option/ ListItem to dropdownlist dynamically

I need to build my DDL dynamically,I get info from DB using JSON (I get the data with no problem) but couldn't show my data in my DDL...
I tried three different ways, nothing changed.. What am I doing wrong ?
//HTML
<asp:DropDownList ID="productDDL" runat="server" CssClass="ddl"></asp:DropDownList>
//Javascript
function creatDDL(data) {
var obj = $.parseJSON(data.Data);
for (var i = 0; i < obj.length; i++) {
$("#productDDL").append("<option>" + obj[i].id + "' - '" + obj[i].name + "</option>");
$("#productDDL").append("<option>"+obj[i].id + "' - '" + obj[i].name+"</option>");
$("#productDDL").append($("<option></option>").html(obj[i].id + "' - '" + obj[i].name));
}
}
I like your third attempt best. Assuming your data is in order, you just need to brush up on the jQuery API.
Here's a working version of what I gather you're trying to do:
function createDDL(data) {
var options = $.parseJSON(data.Data);
$.each(options, function(n, option) {
var $option = $('<option />').text(option.name).val(option.id);
$("#productDDL").append($option);
});
}
Fiddle: http://jsfiddle.net/klenwell/Esr5q/

Categories

Resources