HTML5 - Javascript Sqlite nested transactions - html

this is my first post here, I'm glade to hear from you :-)
Here's my question, please.
In my JqueryMobile web application I've created categories and records.
Each category hosts different records.
What I'd like to print out to the user is the number of records that exists in each category.
For selecting the categories I made a normal transaction
function getAll() {
db.transaction(function (transaction) {
transaction.executeSql(("SELECT * FROM tags"), [], getAllSuccess, errorCB);
});
}
function getAllSuccess(tx, result) {
$('#bags_ul').empty();
var output = '';
$.each(result.rows, function (index) {
var row = result.rows.item(index);
output += '<li><a href="#" class="link_to_tag" data-tagnome="' + row['tagnome'] + '" data-tagtipo="' + row['tagtipo'] + '" data-tagid="' + row['tagid'] + '" >' + row['tagnome'] + '</a></li>';
});
$('#bags_ul').html(output);
$('#bags_ul').listview();
$('#bags_ul').listview('refresh');
}
In my example, the function getAll makes the query, and if get success it execute the getAllSuccess function, that fills in the LI fields of my list.
The problem is that I need to create a query inside the $.each() to get the records of the category.
I've tried to execute another transaction within it, and I can successfully get the number of records thorugh the console.log function, but the problem is that I don't know how to pass it to the "mother" function that in facts pushes the HTML to the page.
Could you please help me?
As you have understood, I need to know the "logic" that is behind this.
I really do thank you very much for your help.
Marco

You could chain the callbacks yourself or use JQuery Deferred.

Related

Will Javascript read returned string as script or treat it as a string?

I am wondering is it possible to run a function that outputs a line that javascript can read and recognize as a variable and not as a string? I have pulled JSON data and what I want to do is to take the object data and dynamically write out variables from it on the fly. I hope this is possible..
function createVar(data){
return "var_" + data.name + data.id + "=_" + data.desc;
//This will return the line :
var itemModel1 = "I no longer vote";
}
I have to say that I don't really recommend this, but it does work.
function createVar(data){
return "var " + data.name + data.id + "='" + data.desc + "'";
}
var exampleData = {name:"itemModel", id:"1", desc:"Today we went to the mall"}
eval(createVar(exampleData));
console.log(itemModel1); //outputs "Today we went to the mall" to the console
I will clarify by saying that if you actually need to generate variable names on the fly, this will do the trick. But I would more closely examine your code to see if there is another way to accomplish what you are trying to do. As always, you have to be very careful with eval, bad things can happen if user input gets passed as your data parameter.

User Search Query to SQL Where Clause

Are there pre-existing libraries that will take a user input and transform it into a SQL WHERE clause?
For example given a database that has columns first_name, last_name, and address the user could input something like:
John State St
and the library would build a query such that it would return rows that match a guy named John that lived on State St (or a guy named State that lived on John St, for that matter).
It could also support things like specifying the column:
first_name:John address:State
I have some simple code to handle some of these cases already but it's getting a little unwieldily. I would think there are some pre-existing solutions to this problem but I'm having a hard time finding them. Generally, the problem is how to enable the user to easily search a structured database with a single input field.
In this matter you can break down string as multiple values using string manipulation, and then search for each word in each column using "or" conditions.
additionally you can define index on columns so as to achieve faster search.
You might have tried this technique since you mentioned, but you have to look up each word in each column
Jquery UI autocomplete could be what you are looking for. the css along with it is also necessary please see this link http://api.jqueryui.com/autocomplete/ for the .js ans css needed.
$( "#myInputBoxId" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
and in search.php
<?php
include 'config.php';
$results =array();
$req = "SELECT product_name "
."FROM table4 "
."WHERE product_name LIKE '%".$_REQUEST['term']."%' LIMIT 5";
$query = mysqli_query($con,$req);
while($row = mysqli_fetch_array($query))
{
array_push($results,$row['product_name']);
}
echo json_encode($results);
}

FB 4.6 - list component -- prepend labels with an item count?

I have a list component that uses a sqlite database as the dataProvider and am able to use labelField to show the data labels just fine... I want to, however, affix an incremental count before the label field so its listed as
1.) item number 1
2.) item number 2 ... etc...
I discovered labelFunct and wrote the following to test it out:
private function lblFunct(value:Object):String
{
return value.id + ") " + value.question;
}
and that shows the automatically assigned database ID before the label text just fine.... my goal is to try to get a COUNT of each item though... I can get the LENGTH of the data provider with
myListComponentID.dataProvider.length
but cant find any info on how to achieve an incremental count. is it possible to construct some sort of for each loop in the labelFunct? can anyone shed any light on this? Thanks in advance.
You're on the right track with the labelFunction. You can use getItemIndex method on your dataProvider to determine the itemIndex of the displayed item:
private function lblFunct(value:Object):String
{
return myListComponentID.dataProvider.getItemIndex(value) + ") " + value.question;
}
with help from the person who responded, I found my way to the solution... the fabel funct ended up looking like this:
private function lblFunct(value:Object):String
{
return (myListComponentID.dataProvider.getItemIndex(value)+1) + ") " + value.question;
}
I added the +1 to compensate for the fact that its zero based. thanks to the responder though, you helped me find my way to the answer. Much appreciated!

Creating a user generated list in flash

I'm trying to create a flash application that will keep track of user generated values. The app should basically allow the user to input the name of the item and it's cost. The total costs should then be added up to show a total value to the user. I can probably figure out how to add the values together, but I'm not really sure how to allow the user to create a list and then allow the user to save it. Can anyone point me towards a tutorial or point me in the right direction?
I am using variables to add user inputed numbers to come up with a total. The first problem is that actionscript 3.0 does not allow variables for texts. I just converted it to 2.0 to fix this. The second problem, is when I test the app and put in my values and click submit, I get NaN in the total values field. Is there a reason why it wouldn't add the values?
Here is the code I used for the submit button:
on (release) {
total = Number(rent) + Number(food) + Number(travel) + Number(entertainment) + Number(bills);
}
Am I missing anything?
Can I give the input text instance names and then give them variables? How are some ways to go about this?
Thanks for the help!
Have an object array, say for example
var stack:Array = new Array();
Then push the item name and it's cost to that array when user inputs, like
stack.push({item:AAA, cost:xx});
So that you can generate the list whenever you want with that array.
You have to see how this works in code. A list in actionscript could be stored inside an array, vector, dictionary or even an Object.
Var myList:Array = [];
myList.push({name: "item 1", cost: 5 });
myList.push({name: "item 2", cost: 7.5 });
If you want to grab the 'product' of "item 1" from the list, you have to create a function for that, lets call it getProductByName
function getProductByName(name:String):Object
{
for each(var product:Object in myList)
{
if (product.name === name) return product;
}
return null; // no match found
}
You can call that function like this:
var product = getProductByName("item 1");
trace(product.cost); // 5
And you can alter the product, so lets make it more expensive
product.cost += 1;
trace(product.cost); // 6
Have fun! If you are using classes, you would create one for the product, with public name and cost, and in that case you'de better use a vector, to ensure working with the right type.
This is what fixed the issue for me in action script 3.0:
myButton.addEventListener(MouseEvent.CLICK, addThem);
function addThem(e:MouseEvent)
{
totalField.text = String ( Number(field1.text) + Number(field2.text) + ....);
}
I also had to name the instances appropriately.

google visualization api, identify tableid in response function

Hmmm, maybe someone can help me out here or point me in the right direction , as i have been banging my head against the wall for a number of days now and dont seem to be gettin anywhere useful.
(and admittedly i'm pretty new with regards to json,objects, google visulization etc)
essentially, i am running 3 different queries on the same page against 3 different fusion tables, which in return are supposed to return an array of 3 different xets of markers.
all is fine, when i run the queries individually and make an array of the markers .
however, running the 3 queries on the same page, i can't seem to find a way to identify the query in the response function.
any hints much appreciated. and i'll be happy to provide more info if needed (tried to get rid of some unneccessary stuff)
this is what i have. thanks
a) calling the function "setFusionData()" with all relevant vars. something like setFusionData("'LatLng','name'", 2729461);
(this is calles 3 times with different variables)
function setFusionData(selColumns,tableId) {
/****
an actual query example is this:
http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
****/
var query = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq='+ encodeURIComponent("SELECT "+selColumns+" FROM "+tableId+"")
);
query.send(getFusionData); //do something with the response
}
function getFusionData(response) {
/**
here, is the problem as i need to get the table id or reqId or anything that is uniquely passed on from "setFusionData" above
also something like
alert(JSON.stringify(response)) does not return any reqId or table id either
***/
/*return rows/columns and add values to an array of markers***/
var numRows = response.getDataTable().getNumberOfRows();
var numCols = response.getDataTable().getNumberOfColumns();
for (i = 0; i < numRows; i++) {
/* add markers to array etc this works fine***/
}
}
i also tried something like this:
function setFusionData(selColumns,tableId) {
......
query.send(getFusionData({reqId:tableId}));
}
function getFusionData(response) {
alert(response['reqId']);//returns tableId. but how do i get the tableData ?
}
with wich i can get the reqId, but not the table*Data*. So I am only able to get either id or data :(
----edit----------------
after messing around a bit more (see below) it appears that the key/value pairs that get returned when typing the query into the browser directly are different than what gets returned by the call from the script...i.e the following
http ://www.google.com/fusiontables/gvizdata?tqx=reqId:1234&tq="select+'LatLng','name'+from+2729461"
typed directly into the browser bar will return
version:'0.5',reqId:'1234',status:'ok',table etc
however, calling the same from within the script returns something like
{
"rj":"0.5","ef":"ok","pb":[],"qb":[],"h":"{"cols":
[{"id":"col2","label":"LatLng","type":"string"},{"id":"col1","label":"name","type":"string"}],
"rows":
[{"c":[{"v":"47.20572,12.70414"},
{"v":"Hohe Tauern"}]},{"c":[{"v":"47.5530395,12.925611"},{"v":"Berchtesgaden"}]},{"c":[{"v":"47.5585405,14.61887"},{"v":"Gesu00e4use"}]}],
"p":{"totalrows":3}
}"
}
, so no 'reqId' but only some cryptic keys (without one that looks like the reqId either)...... anyone any idea why that would/could be ?
Sometimes you can figure it out by just looking at the JSON response, your sample request returns:
google.visualization.Query.setResponse({
version:'0.5',
reqId:'1234',
status:'ok',
table: {
...
}
})
You already got response.reqId to identify which request is this the response for, now you can use response.table to create a new DataTable instance:
var dt = new google.visualization.DataTable(response.table);
Or, since you have multiple tables, put then in an array indexed with the reqId
tables[response.reqId] = new google.visualization.DataTable(response.table);
You'd do var tables = new Array() before calling setFusionData() for the first time.