I am pulling data from my remote database and get this JSON data:
{"list1":{"id":1, "item":"testobj1"},"list2":{"id":2, "item":"testobj2"},"list3":{"id":3,
"item":"testobj3"},"list4":{"id":4, "item":"testobj4"},"list5":{"id":5, "item":"testobj5"}}
I can now loop through the objects in the data and display a list of objects on my screen. It works fine:
var d = JSON.parse(hr.responseText);
databox.innerHTML = "";
for (var o in d) {
if (d[o].item) {
databox.innerHTML += '<p>' + d[o].item + '</p>' + '<hr>';
}
}
Now however, I would like to insert this data into my Sqlite database. I am not quite sure how I can tell the loop that 'd[o].id' and 'd[o].item' are the items I would like insert into my db.
db.transaction(function(tx) {
var sql = "INSERT OR REPLACE INTO testTable (id, item) " + "VALUES
(?, ?)";
log('Inserting or Updating in local database:');
var d = JSON.parse(hr.responseText);
var id = d[o].id;
var item = d[o].item;
for (var i = 0; i < d.length; i++) {
log(d[o].id + ' ' + d[o].item);
var params = [d[o].id, d[o].item];
tx.executeSql(sql, params);
}
log('Synchronization complete (' + d + ' items synchronized)');
}, this.txErrorHandler, function(tx) {
callback();
});
I hope somebody can take a look at this loop and tell me where did I go wrong. Many thanks in advance!
You're iterating over d as if it's an array rather than an object. Something like this is probably what you're looking for:
var d = JSON.parse(hr.responseText);
for (var o in d) {
var params = [d[o].id, d[o].item];
tx.executeSql(sql, params);
}
Related
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
I am trying to make this javascript variable with some data from an array , but i cant figure out the right syntax to make this work..
certifications will be "Win7,Win8,PDI"
var myArray = certifications.split(",");
var data = "[{" +
for (var i in myArray)
" "id":i,"text":myArray[i]}, " +
"}]";
I'm hoping to get my data variable to look something like:
var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";
Try this:
var data = JSON.stringify(certifications.split(",").map(function(value, index) {
return {
id: index,
text: value
};
}));
Maybe += is what your looking for:
var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";
for (var i in myArray) {
data += " " +
"id" +":"+i+","+
"text" + ":"+myArray[i]+"}, ";
}
data += "}]";
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.
I have a problem when trying to store the results of a select query into an array with java script .
the problem is that inside the function the array is containing the right values but outside it's empty , even when i used a global var it's still empty !!!
db.transaction(function (transaction) {
var sql = "SELECT * FROM Question where idEnq=" + idEn;
transaction.executeSql(sql, undefined, function (transaction, result) {
var res = document.getElementById('results');
res.innerHTML = "<ul>";
if (result.rows.length) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
ch[i] = new qu(row.id, row.text, row.type);
res.innerHTML += '<li>' + row.id + ' ' + ch[i].text + ' ' + ch[i].type + '</li>';
}
tablo = ch;
} else {
alert("No choices");
res.innerHTML += "<li> No choices </li>";
}
res.innerHTML += "</ul>";
}, onError);
}); // here the ch and the tablo array are empty
You are using asynchronous functions. Anything that wants to use the data "returned" by those functions need to be in the callback. Of course you can assign this data e.g. to a global variable, but that variable will only have the value after the callback has run (asynchronously).
you're new so have look here http://pietschsoft.com/post/2008/02/JavaScript-Function-Tips-and-Tricks.aspx
there's a part talking about calling JavaScript Function asynchronously
I am trying to write a Javascript function that obtains an array of unique ids from an sqlite database & then passes them to be used in another function where the ids can be used in another sql query, they also form part of a dynamically created list.
I have managed to pass the ids row['id'] to the array variable window.symp[i]. But I have not been able to access them correctly in the second function below, the second function correctly uses the ids to create the dynamic html but the variable passed to the sqlite query either fails or is the same value in all the list items created. Any help would be greatly appreciated - I have included both functions below:
function showContent() {
db.transaction(function (tx) {
tx.executeSql("SELECT id, notes FROM webkit WHERE notes LIKE 'A%'", [], function (tx, result) {
var notesanode = document.getElementById('notesa');
notesanode.innerHTML = "";
for (var i = 0; i < result.rows.length; ++i) {
var row = result.rows.item(i);
window.symp[i] = i;
window.symp[i] = row['id'];
var noteadiv = document.createElement('div');
noteadiv.innerHTML = '<li class=\"arrow\"><a id=\"0\" onClick=\"showSymptoms()\" href=\"#symptoms\">' + row['notes'] + " " + row['id'] + '</a></li>';
notesanode.appendChild(noteadiv);
}
}, function (tx, error) {
alert('Failed to retrieve notes from database - ' + error.message);
return;
});
});
}
function showSymptoms() {
db.transaction(function (tx) {
tx.executeSql("SELECT sid, symptom FROM slinks WHERE id LIKE ('" + symp + "')", [], function (tx, result) {
var symptomnode = document.getElementById('symptomid');
symptomnode.innerHTML = "";
for (var i = 0; i < result.rows.length; ++i) {
var row = result.rows.item(i);
var symptomdiv = document.createElement('div');
symptomdiv.innerHTML = '<p><label> <input type=checkbox>' + row['symptom'] + '</label></p>';
symptomnode.appendChild(symptomdiv);
}
}, function (tx, error) {
alert('Failed to retrieve notes from database - ' + error.message);
return;
});
});
}
I see two things:
The main issue is that you need
"SELECT sid, symptom FROM slinks WHERE id LIKE ('" + window.symp.join(',') + "')"
instead of what you have up there.
The second issue is that you have
window.symp[i] = i;
window.symp[i] = row['id'];
you can just go ahead and remove window.symp[i] = i; because it gets immediately overwritten by the line that follows it.