Search code examples
javascriptjquerycordovaphonegapweb-sql

Accessing WebSQL Database object in PhoneGap


I am trying to access WebSQL database results using PhoneGap Developer App, but I cannot seem to access the object correctly. Here is an example piece of code:

db.transaction(function(tx) {
    tx.executeSql('SELECT * FROM ' + table, [],
    function (transaction, resultSet) {
        console.log(resultSet.rows);
    }, function (transaction, error) {
        console.log(error);
    });
});

This block works perfectly fine in Chrome while testing the PhoneGap app via the PhoneGap CLI. It returns the object in the console and the CLI says [object SQLResultSetRowList]. I can then access a specific row by calling:

console.log(resultSet.rows.item(0));

This works fine in both the desktop CLI and developer app. What I want to do though, is to iterate through the results using jQuery $.each:

$.each(resultSet.rows, function (k,v) {
    console.log(JSON.stringify(v));
});

This is where I encounter a problem. In Desktop Chrome and using the CLI, each row is correctly printed to the console as a JSON string of key => value pairs. But when I try to run the exact same code using the PhoneGap Developer App on my testing device, the console instead only prints the following: "100" which is the "length" key of the result set, and an empty output (the corresponding key being "item").

What is the correct way to iterate through the resultSet object? For reference, I am using an iPhone X on iOS 11 as my testing device.


Solution

  • I ended up working around this issue by building an object from scratch using the resultSet data:

    function getIterableObjectFromResult(resultSet) {
        for (var i = 0, data = {}; i < resultSet.rows.length; i++) {
            data[i] = resultSet.rows.item(i);
        }
        return data;
    }
    

    The resulting output can then be iterated correctly in the PhoneGap Developer app.