There's a lot of code here, but the question has to do with the for loop at the bottom.
var dbo = openDatabase('xxx','1.0','myDatabase', 1048576);
var DropTableDeferred = new $.Deferred();
var CreateTableDeferred = new $.Deferred();
var InsertDeferred = new $.Deferred();
var SelectDeferred = new $.Deferred();
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'drop table myTable;'
,[]
,DropTableDeferred.resolve()
);
});
DropTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'CREATE TABLE IF NOT EXISTS myTable'
+ '(xxxID Integer NOT NULL PRIMARY KEY'
+ ',xxxName Varchar(128)'
+ ');'
,[]
,CreateTableDeferred.resolve()
);
});
});
CreateTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(1,'A')");
myTrans.executeSql("INSERT INTO myTable(xxxID,xxxName) VALUES(2,'B')");
myTrans.executeSql(
"INSERT INTO myTable(xxxID,xxxName) VALUES(3,'C')",
[],
InsertDeferred.resolve()
);
});
});
InsertDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'SELECT * FROM myTable',
[],
function(tx, result) {
SelectDeferred.resolve(result);
}
);
});
});
SelectDeferred.done(function(result) {
var X = $('#result-template').html();
var template = Handlebars.compile(X);
var data = [];
for(var i=0;i < result.rows.length; i++) {
data.push(result.rows.item(i));
}
$('ul').append(template(data));
});
Q: Do I need to build a data array in order to call template(data), or can I pass the result variable directly?
And by 'result variable', what I mean is: result.rows, or result.rows.item, or some other combination.
Yes the value has passed directly in my html&javascript only project. In the code below, I get the results of the Sql and filling a dropdown box's options.
function fillLectureFromDB(tx) {
tx.executeSql('SELECT * FROM LECTURE', [], successFill, errorFill);
}
function successFill(tx, results) {
var len = results.rows.length;
for (var i=0; i<len; i++){
var elOptNew = document.createElement('option');
elOptNew.text = results.rows.item(i).code;
elOptNew.value = results.rows.item(i).code;
var elSel = document.getElementById('slExCode');
elSel.add(elOptNew, null);
}
}
IMHO you can, but to tell you the truth, it would've taken less time for you to try it out then to post the question. Just try:
$('ul').append(template(result.rows));
Related
I don't know why the value in my div appears only one time ...
function nbProduct(sel) {
var nbProduct = sel.options[sel.selectedIndex].text
$('#tableFacture').remove();
$('#tableFacture').remove();
for(var i =0;i < nbProduct;i++){
var nFacture = i + 1
$("#product").append("<table id='tableFacture'></table>")
$("#tableFacture").append("<th scope='row' id='rowProduct"+i+"'>Produit N°"+nFacture+"</th")
$("#rowProduct"+i+"").append("<div class='row' syle='margin-top: 40px;' id='"+i+"'><select onChange='typeProduct(this);'><option></option><option value='"+i+"'>Velo</option><option value='"+i+"'>Trottinette</option><option value='"+i+"'>Accessoires</option></select></div>")
}
function typeProduct(sel) {
var typeOfProduct = sel.options[sel.selectedIndex].text
var nbDiv = sel.options[sel.selectedIndex].value
if (typeOfProduct == 'Velo'){
$("#"+nbDiv+"").append("<div class='containerFacture><select id='factureVelo'><option></option></select></div>")
client.query('SELECT * FROM core_velo ORDER BY model DESC',(err,res)=>{
for(var i =0;i < res.rows.length;i++){
var item = res.rows[i];
var model = item['model']
$("#factureVelo").append("<option>"+model+"</option>")
}
client.end()
})
}
};
picture of my problem
And I have an other problem, how use grid in electronjs ? because col-md/sm/XS ... do not work.
You to try use:
function typeProduct(sel) {
var typeOfProduct = sel.options[sel.selectedIndex].text
var nbDiv = sel.options[sel.selectedIndex].value
if (typeOfProduct == 'Velo'){
$("#"+nbDiv+"").append("<div class='containerFacture col-xs-2 offset-xs-1'><select id='factureVelo'><option></option></select></div>")
client.query('SELECT * FROM core_velo ORDER BY model DESC',(err,res)=>{
var model ="";
$.each(res, function(index, value){
model += value.model;
})
$("#factureVelo").append("<option>"+model+"</option>")
}
client.end()
})
}
};
I'm new to Angular and my experience with Javascript is not very extensive. I am failing to show data in ngGrid using following code. What is the problem?
In essence. I am loading data from a web-service, performing a transform (pivot) on it and then I want to present it in a grid.
Please see the following
app.js -> starting poing
var konstruktApp= angular.module('konstruktApp',['ngGrid']);
dataService.js -> web service call
'use strict';
konstruktApp.service('DataService',function DataService($http){
var callHttp = function(){
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get("http://83.250.197.214/konstrukt.service/Konstrukt.SL.DummyBudgetService.svc/GetDummyBudgetData/");
};
return {
getDummyData: callHttp
};
});
ngGridController.js -> where the logic resides...
$scope.getData = DataService.getDummyData;
$scope.gridOptions = {data:'result'};
var getData = function() {
$scope.getData().then(function (response) {
var res = pivotData(response.data);
$scope.result = res.data.PivotedRows;
$scope.columns = res.cols;
console.log('from the success handler at ' + new Date());
}, function (reason) {
console.log('failed: ');
console.log(reason);
});
};
..and here is the logic that "pivots" the data
var pivotData = function(data) {
var firstColumn = "Dim1";
var secondColumn = "Period";
var columns = [];
columns.push({
field: firstColumn,
enableCellEdit: false
});
var pivotedArray = {};
pivotedArray.PivotedRows = [];
var rowItems = [];
var rowArray = {};
var previusFirstColumnValue = -1;
var firstColumnValue = 1;
//for each row
for (var i = 0; i < data.Rows.length; i = i + 1) {
//firstColumnValue = $scope.dataCollection.Rows[i].FindCell.Cells[firstColumn].Value;
firstColumnValue = findCell(data.Rows[i].Cells, firstColumn).Value;
//var secondColumnValue = data.Rows[i].Cells[secondColumn].Value;
var secondColumnValue = findCell(data.Rows[i].Cells, secondColumn).Value;
//if first column value has changed, add new row
if (firstColumnValue != previusFirstColumnValue) {
if (i !== 0) {
for (var j = 0; j < rowItems.length; j = j + 1) {
rowArray[rowItems[j].name] = rowItems[j].value;
}
pivotedArray.PivotedRows.push( rowArray);
rowArray = {};
rowItems = [];
}
rowItems.push({
name: firstColumn,
//value: $scope.dataCollection.Rows[i].Cells[firstColumn].Value
value: findCell(data.Rows[i].Cells, firstColumn).Value
});
}
//if (columns.indexOf({field: secondColumnValue}) == -1) {
if (i < 12) {
columns.push({
field: secondColumnValue,
editableCellTemplate: "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-blur=\"lostFocus()\" ng-model=\"COL_FIELD\" ng-change=\"dataChanged(col,row,row.entity)\"/>",
enableCellEdit: true
});
}
rowItems.push({
name: secondColumnValue,
value: findCell(data.Rows[i].Cells, secondColumn).Value
});
previusFirstColumnValue = firstColumnValue;
}
for (var k = 0; k < rowItems.length; k = k + 1) {
rowArray[rowItems[k].name] = rowItems[k].value;
}
// $scope.columns = columns;
pivotedArray.PivotedRows.push( rowArray);
return {data: pivotedArray, cols: columns};
};
plnkr: http://plnkr.co/edit/ZqC7696xGbUtuWGIvnYs?p=preview
EDIT: The data correlation rows<-> columns is correct, I suspect there is something wrong with data in the pivotedArray.PivotedRows array.
It turned out that moving the code to a new plnkr made the difference. Now, thats a few hours of my life that I want back :)
I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});
I have a mobile app in HTML5 that is using the websql database. I have a data.js file with a bunch of functions for doing various CRUD jobs with the database. I've never had this problem until I got to wiring this function. Basically the app is for creating quotes for tradesmen and the function I'm writing is getting the quote and quote lines, converting them into and array of JSON objects and ajaxing them to a web app.
For some reason my db.transaction's are not being executed. Can you help me figure out why? The db exists as other functions are calling this exact SQL. But it works for them and not this one:
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
tx.executeSql("SELECT * FROM quote_header WHERE id = ?", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = areas.area_id JOIN features ON quote_line.feature_id = features.feature_id JOIN products ON quote_line.product_id = products.product_id WHERE quote_line.quote_id = ?", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
I have both success and fail callbacks but neither is responding.
Also this is the first time I'm posting JSON from a JS app so feel free to comment.
Thanks,
Billy
Copy this edited codes and see if it works
function syncQuote(){
var quote_id = localStorage["quote_id"];
var header = new Array(); // holds id, created, appointment_id
db = openDatabase("Quote", "0.1", "A collection of quotes.", 200000);
if(!db){
console.log('Failed to connect to database.');
}
console.log('Getting quote header data.');
db.transaction(
function(tx) {
// CORRECTION 1: THE ? IS MEANT TO BE IN A BRACKET
tx.executeSql("SELECT * FROM quote_header WHERE id = (?)", [quote_id],
function(tx, results) {
var len = results.rows.length;
for(var i=0; i< len; i++){
alert('booyah!');
header['quote_id'] = results.rows.item(i).id;
header['appointment_id'] = results.rows.item(i).appointment_id;
header['created'] = results.rows.item(i).created;
}
});
},
function(tx, error){
console.log(error.message);
},
//CORRECTION 2
//THERE IS MEANT TO BE A SUCCESS CALL BACK FUNCTION HERE
function(){
console.log( 'Query Completed' )
}
);
// now get all quote lines for this quote
var lines = new Array();
console.log('getting quote lines');
db.transaction(
function(tx) {
// CORRECTION 3: WRONG CALL METHOD AND NONE-USE OF BRACKETS and QOUTES
tx.executeSql("SELECT DISTINCT areas.label as area, features.label as feature, products.label as product, hours, price, colour FROM quote_line JOIN areas ON quote_line.area_id = 'areas.area_id' JOIN features ON quote_line.feature_id = 'features.feature_id' JOIN products ON quote_line.product_id = 'products.product_id' WHERE quote_line.quote_id = (?)", [quote_id],
function(tx, results) {
len = results.rows.length;
for(var i=0; i< len; i++){
var area= results.rows.item(i).area;
var feature= results.rows.item(i).feature;
var product= results.rows.item(i).product;
var hours= results.rows.item(i).hours;
var price= results.rows.item(i).price;
var colour= results.rows.item(i).colour;
lines[i] = new Array(6);
lines[i][0] = area;
lines[i][1] = feature;
lines[i][2] = product;
lines[i][3] = hours;
lines[i][4] = price;
lines[i][5] = colour;
}
},
function(tx, error){
console.log(error.message);
}
);
}
);
var data = new Array(2);
data[0] = JSON.stringify(header);
data[1] = JSON.stringify(lines);
alert(data[0]);
alert(data[1]);
// post data to web app
var url = "http://*****.com/import_quote";
$.ajax({
type: 'POST',
url: url,
data: data,
success: quote_sync_success,
dataType: 'JSON'
});
}
have you tried throwing console.log()'s in at the start of your success callbacks? if len is 0 in those, you wouldn't get any output from them as is
Here is the code
onError = function(tx, e) {
alert('Something unexpected happened: ' + e.message );
}
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
webdb.transaction(function(tx) {
tx.executeSql('SELECT * FROM colours',
[],
function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
},
onError);
});
/**
* the array looks like [[1,'red'],[2,'white'],[3,'black'] ...]
*/
var ColourStore = new Ext.data.ArrayStore({fields: ['key', 'val'],
data: colourArray});
The table "colours" contain colour name and hash code. And it was suppose to be use by a ExtJS Ext.data.ArrayStore then populate other drop downs on a massive form.
My problem is - I couldn't get the data back as an array. The variable "colourArray" is empty ... I know I hit some javascript closure , loop problem ... but just couldn't figure out how to get that inner loop value back. Try a lot of return -> return -> return function and more return. None of them works.
executeSQL is asynchronous. You need to create ColourStore in the function(tx,rs) callback function. If you need the data available globally, you can't init your app until executeSQL calls the callback function. Example:
Ext.onReady( function() {
var webdb = openDatabase(dbName, '1.0' , dbDesc , dbSize);
var colourArray = new Array();
var ColourStore;
webdb.transaction( function(tx) {
tx.executeSql('SELECT * FROM colours',
[], function(tx,rs) {
var ctn = rs.rows.length;
for (var i=0; i < ctn; i++) {
var row = rs.rows.item(i);
colourArray.push([row.id , row.title]);
}
//INIT YOUR APP HERE IN ORDER TO HAVE ACCESS TO colourArray values
ColourStore = new Ext....
YourApp.init();
},
onError);
});
}, this);