I've got the following JSON structure that defines a table and it's data.
var arrTable =
[{"table": "tblConfig",
"def":
[{"column": "Property", "type": "TEXT NOT NULL"},
{"column": "Value", "type": "TEXT NOT NULL"}],
"data":
[{"Property": "VersionNumber", "Value": "1.0"},
{"Property": "ReleaseDate", "Value": "2010-01-01"}]
}]
The code describes a table named "tblConfig" with two columns, "Property" and "Value" both are type "TEXT NOT NULL". The table has two rows of data.
Property_______Value_____
VersionNumber 1.0
ReleaseDate 2010-01-01
Below is my Javascript code to create and populate the table. It builds the create table SQL great but I'm having trouble with the populate function.
dbController.updateDatabase = function () {
this.db.transaction(function (transaction) {
//load data.json
var dbDefs = dbController.jsonObject(url + "data.json")
//parse array "table"
eval(dbDefs);
for (var i in arrTables) {
createTable(arrTables[i].table, arrTables[i].def, arrTables[i].data);
}
//create table
function createTable(table, arrDef, arrData) {
var arrColumns = [];
var strSQL = "CREATE TABLE " + table + " (";
for (var j in arrDef) {
arrColumns.push(arrDef[j].column);
strSQL += arrDef[j].column + " " + arrDef[j].type + ", ";
}
strSQL = strSQL.substring(0, strSQL.lastIndexOf(",")) + ")";
transaction.executeSql(strSQL, [],
function () {
console.log(table + " created.");
populateTable(table, arrData);
return;
},
dbController.errorHandler
);
}
//populate table
function populateTable(table, arrData) {
...
}
});
};
I want to be able to get the column names ("Property" & "Value") out of the "data" object and use them in the insert SQL string. I thought something like this would work.
//populate table
function populateTable(table, arrColumns, arrData) {
var strVal;
var arrVal;
for (var k in arrData) {
strVal = "?,";
arrVal.push(arrData[k]. ~~ KEY VALUE NAME ~~ )
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.lastIndexOf(",") + ");";
transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler);
console.log(" " + table + " populated.");
}
The bugger is the bolded statement. I've tried using .hasOwnProperty() on arrData but that only returns 0 and 1, not the words "Property" and "Value". I don't want to use the "arrData[k].Property" notation because there are many more tables in the schema and I don't want to write create and insert statements for each table.
Any help is greatly appreciated.
Thanks to everyone for their help and head-scratching due to my late-night post. My intention with this function was to have a JSON object that defined multiple tables and held the table's data. Since none of the tables have the same number of columns or column names I had to devise a way of getting the data out of "data" without using the object.member syntax. I had forgotten about the object["member"] syntax.
Here's the solution.
dbController.updateDatabase = function (a) {
this.db.transaction(function (transaction) {
//load data.json
var dbDefs = dbController.jsonObject(dbController.dbFolder + "data.json")
//parse array "table"
eval(dbDefs);
for(var i in arrTables) {
createTable(arrTables[i].table, arrTables[i].def, arrTables[i].data);
}
//create table
function createTable(table, arrDef, arrData){
var arrColumns = [];
var strSQL = "Create Table " + table + " (";
for(var j in arrDef) {
arrColumns.push(arrDef[j].column);
strSQL += arrDef[j].column + " " + arrDef[j].type + ", ";
}
strSQL = strSQL.substring(0, strSQL.lastIndexOf(",")) + ")";
transaction.executeSql(strSQL, [],
function() {
console.log(table + " created.");
populateTable(table, arrColumns, arrData);
return;
},
dbController.errorHandler
);
}
//populate table
function populateTable(table, arrColumns, arrData) {
for (var k in arrData) {
var arrVal = [];
var strVal = "";
for (var l = 0; l < arrColumns.length; l++) {
strVal += "?,";
arrVal.push(arrData[k][arrColumns[l]])
}
var strSQL = "Insert Into "+table+" (" + arrColumns.toString()+") ";
strSQL += "Values ("+strVal.substring(0, strVal.lastIndexOf(","))+");";
transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler);
}
console.log(" " + table + " populated.");
}
});
};
I'm making some assumptions here, but try changing:
for (var k in arrData) {
strVal = "?,";
arrVal.push(arrData[k]. ~~ KEY VALUE NAME ~~ )
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.lastIndexOf(",") + ");";
to:
for (var i =0; i < arrColumns.length; ++i) strVal += ',?';
for (var k in arrData)
{
arrVal[k] = [];
for (var i in arrColumns)
arrVal[k].push (arrData[k][arrColumns[i]]);
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.substr(1) + ");";
If I'm correct in thinking that transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler); accepts multiple records, then this should work fine. Otherwise, call
transaction.executeSql(strSQL, arrVal[0], null, dbController.errorHandler);
instead
Don't you just want to look at the first row of your 'data' element and enumerate through those keys (assuming all the rows are the same)?
for (var k in arrData[0]) {...
In Javascript, and time you have an object with members that you can access via obj.member, you can also access it as obj["member"]. Objects in JavaScript are essentially just hash tables with the ability to call methods on them (which are also just entries in the hash table), and a prototype based inheritance system.
Anyhow, that means that you can use for ... in to iterate over the properties in that hash table, and pull out the keys.
So, if I understand what you're trying to do correctly, you could just do something like this (note that the structure of this loop is somewhat different than the one in your question, as you're going to need one INSERT statement for each row to insert, while your loop had the construction of the INSERT statement outside of the loop over the data rows):
function populateTable(table, data) {
for (var k in data) {
var queryArgs = [];
var argArray = [];
var columns = [];
for (var col in data[k]) {
queryArgs.push('?');
columns.push(col);
argArray.push(data[k][col]);
}
var SQL = "INSERT INTO " + table + " (" + columns + ") VALUES " +
"(" + queryArgs + ");";
alert(SQL + " [" + argArray + "]")
}
}
Related
I am trying to the splice method but it is not working properly want to delete one user but it is deleting 2.
Also want to add the binary search button
this is the requirement for binary search
Replace the sequential access algorithm to operate on the arrays with a binary search algorithm.
To implement this, the array’s data must be sorted. You may refer to an online example available at Array.prototype.sort() to learn about sorting data in arrays.
function Display_Athlete() {
var text = "<hr/>";
for (let i = 0; i < athlete_name.length; i++) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
document.getElementById("message").innerHTML = text;
}
//Created function to remove the user
function Remove_Athlete() {
var person = prompt("Enter the name to remove the Athlete");
for (let i = 0; i < athlete_name.length; i++) {
athlete_name.splice(person - 1, 1);
athlete_height.splice(person - 1, 1);
alert(" Athlete_name " + athlete_name + " Athlete_height " + athlete_height + " is removed ");
}
}
//Create the function to find the user
function Find_Athlete() {
var person = prompt("Enter the name to Find the Athlete");
var text = "";
for (let i = 0; i < athlete_name.length; i++) {
if (athlete_name[i] == person) {
text += "Athlete No - " + (i + 1) + ", Athlete Name is " + athlete_name[i]
+ " and height is " + athlete_height[i] + "<br>";
}
}
document.getElementById("message").innerHTML = text;
if (text == "")
alert(`${person} Invalid Athlete name`);
return "";
}
function Binary_Search(){
}
Through ajax response I'm passing array data from controller to blade.
On Ajax success I'm looping through array with 2 elements and concatenating string to display later on in my bootstrap popover.
success: function (data) {
var content = "";
var num = 1;
for (var i = 0; i < data.length; i++) {
content = content.concat(num + "." + " " + data[i]);
num++;
}
$("#content").popover({content: content});
}
Result:
I would like to add new line, so that each item or "artikel" would be displayed in new line e.g. :
1.Artikel...
2.Artikel...
I tried to add "\n" (as below) or html break but nothing works, it only appends as string.
content = content.concat(num + "." + " " + data[i] + "\n");
Use this:
content.concat(num + "." + " " + data[i] + "<br/>");
And this:
$("#content").popover({ html:true, content: content });
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.
I have an array that looks like this (using var_dump in php):
string '[{"US":"2"},{"England":"0"},{"Mexico":"0"},{"France":"0"},{"Canada":"0"},{"Spain":"0"},{"Italy":"0"},{"Australia":"0"},{"Japan":"0"},{"China":"0"},{"Korea":"0"}]'
I need to extract both columns in javascript but I obviously fail whatever I tried
This is what I tried so far:
var dbdata = <?php echo json_encode($dataset1); ?>;
for (var key in dbdata) {
for (var key2 in dbdata[key]) {
alert("Country " + key2 + " No of member is " + key);
}
}
I get the country right, but the key is the index not the column value. How should be be fixed?
Thanks
dbdata[key][key2]
Contains the number.
http://jsfiddle.net/NPTQB/
var data = [{"US":"2"},{"England":"0"},{"Mexico":"0"},{"France":"0"},{"Canada":"0"},{"Spain":"0"},{"Italy":"0"},{"Australia":"0"},{"Japan":"0"},{"China":"0"},{"Korea":"0"}];
for (var key in data) {
for (var key2 in data[key]) {
alert("Country " + key2 + " No of member is " + data[key][key2]);
}
}
I am using a SQLite database in my PhoneGap application. I am able to populate the database, extract the database and also print it using console.log
Here is the code
function extractFromDB(){
var db = window.openDatabase("hospitalsDB", "1.0", "HospitalsDB", false);
db.transaction(queryDB, errorCB);
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM hospitals', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var len = results.rows.length;
console.log("DEMO table: " + len + " rows found.");
for (var i=0; i<len; i++){
console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data);
}
}
My question is, how do I print this data onto the html page ?
If i get your question in right way.Assume you have a <div> in your html page:
var resultDiv = $('#mydiv');
var data = undefined;
for (var i=0; i<len; i++){
data = "Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data;
resultDiv.append(data + "<br>")
This will write all the data into a div in your html page. A simple example smilar to your one: JSFIDDLE
function querySuccess(tx, results) {
<!-- its good programming to check the length of rows returned by sqlite DB.-->
var htmlstring = "";
if (results != null && results.rows != null && results.rows.length > 0) {
for ( var i = 0;i <results.rows.length;i++)
{
htmlstring+= '<div class="ui-grid-a">';
htmlstring += '<div class="ui-block-a">'+results.rows.item(i).id+'</div>';
htmlstring+= '</div>';
}
$("#divholderfordata").empty().append(htmlstring).trigger('create');
}
else
{console.log("no records inserted in DB");}
}
where you can define "div" with id "divholderfordata" in your html code this code will work better as far as "UI" is concerned because it also includes "jquery-mobile" code
hope it will help you.