Exploring the integration of SQLite in a PhoneGap mobile application

I've been working on a phonegap app and trying to implement sqlite functionality. Despite following a tutorial, it's not functioning properly.

Take a look at my code:

<script type="text/javascript">
//add listener when device ready
document.addEventListener("deviceready", onDeviceReady, false);
var db;
var dbex; // Hoping 
to access DB outside populateDB function

//function will be called when device is ready
function onDeviceReady(){
    db = window.openDatabase("Test_DB", "1.0", "My DB for Test", 200000); //will create database Test_DB or open it
    db.transaction(populateDB, errorCB, successCB);
}

//create table and insert some records
function populateDB(tx) {
    tx.executeSql('CREATE TABLE IF NOT EXISTS Usuario (id INTEGER PRIMARY KEY AUTOINCREMENT, Nombre TEXT NOT NULL, Edad INTEGER NOT NULL, Email TEXT, Localidad TEXT, Pais TEXT NOT NULL');

    tx.executeSql('CREATE TABLE IF NOT EXISTS Datos (id INTEGER PRIMARY KEY AUTOINCREMENT, text_one TEXT, text_two TEXT, text_emg TEXT, color TEXT)');

    for (var i = 0; i > 4; i++) {
        tx.executeSql('INSERT INTO Datos(text_one,text_two,text_emg, color) VALUES ("rouge", "vermelho", "-", "red")');
    }; 
    dbex = tx;
}

//function for handling errors
function errorCB(err) {
    $("#siguiente").html('error');
    alert("Error processing SQL: "+err.code);
}

//function for successful transactions
function successCB() {
    $("#siguiente").html('success');
    alert("Success!");
    db.transaction(queryDB,errorCB);
}

//select all from Usuario
function queryDB(tx){
    tx.executeSql('SELECT * FROM Usuario',[],querySuccess,errorCB);
}

var submitButton = document.getElementById("registro");

submitButton.disabled = true;

submitButton.onclick = function(){
    var nombre = document.getElementById("nombre");
    var edad = document.getElementById("edad");
    var email = document.getElementById("email");
    var localidad = document.getElementById("localidad");
    var pais = document.getElementById("pais");
    dbex.executeSql('INSERT INTO Usuario(Nombre,Edad,Email,Localidad,Pais) VALUES (nombre.value,edad.value,email.value,localidad.value,pais.value)');


    function querySuccess(tx,result){
        console.log("querySuccess");
        $("#siguiente").html('result');
    }
}

function doCheck(){
    var allFilled = true;

    var inputs = document.getElementsByTagName('input');
    for(var i=0; i<inputs.length; i++){
        if(inputs[i].value == ''){
            allFilled = false;
            break;
        }
    }

    submitButton.disabled = !allFilled;
}

window.onload = function(){
    var inputs = document.getElementsByTagName('input');
    for(var i=0; i<inputs.length; i++){
        if(inputs[i].type == "text"){
            inputs[i].onkeyup = doCheck;
            inputs[i].onblur = doCheck;
        }
    }
};

However, I'm encountering this error message:

Uncaught TypeError: Cannot call method 'executeSql' of undefined index.html:134
  pinchado.onclick

Any suggestions on how to resolve this issue?

Answer №1

Consider placing the initialization of the variable db inside the onDeviceReady() function to ensure it is initialized correctly.

function onDeviceReady() {
    db=window.openDatabase("Trial_DB", "1.0", "My DB for Test", 200000);
    db.transaction(populateDB, errorCB, successCB);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

Using javascript, retrieve the JSON values for each level

I need help using a recursive function in JavaScript to retrieve the last key value pair from a simple JSON object. Here is an example JSON object: { 'a': { 'b': { 'c': 12, 'd': 'Hello World& ...

Dev4: utilizing scaleOrdinal for color mapping and selection

I have developed a code that generates line graphs on an SVG canvas, however, I am facing difficulties in altering the colors as I defined using the d3.scaleOrdinal function. Despite defining 12 distinct colors, the output I am getting looks like this. Is ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...

Setting up scheduled MongoDB collection cleanup tasks within a Meteor application

After developing an app to streamline form submissions for my team, I encountered a problem during testing. Meteor would refresh the page randomly, causing loss of data entered in forms. To solve this, I devised a two-way data binding method by creating a ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

Activate the Vue checkbox option

Starting out with Vue and web development. I am currently building my app using Laravel and Vue. This is the code snippet I am working on: created: function () { let self = this; self.setActive('tab1'); axios.get(this.$apiAdress + '/api/tas ...

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Ways to trigger a function once all elements have been successfully mounted

Currently, I am incorporating VueJS with the Vue Router and a JavaScript uniform module to enhance the appearance of select boxes, checkboxes, and other form elements by wrapping them in a new element for better styling options. How can I efficiently appl ...

Check an array of objects for duplicate key-value pairs by cross-referencing other key-value pairs within the array using JavaScript

let selectedFruit = "mango" let fruitArray = [{fruit:"apple",locale:"US"}, {fruit:"orange",locale:"US"}, {fruit:"banana",locale:"US"}, {fruit:"apple",locale:"US"}, {fruit:"orange",locale:"IT"}, {fruit:"apple",locale: ...

Retrieve the concealed division element's HTML content along with its formatting

Help needed with appending a hidden div with its styles intact. Despite using the code provided below, the appended div does not retain its styles. Any suggestions for an alternative method? var warningMessage = $('#warningDiv').html() fun ...

confrontation arising between two PHP scripts due to conflicting functionalities within the MetaSlider plugin

Seeking assistance with the WordPress plugin metaslider, specifically involving two code snippets. The first one implements the "ken burns effect" while the second disables the "pause on action" feature. Strangely, the "pause on action" seems to interfere ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

Do you find encodeURIComponent to be extremely helpful?

I'm still puzzled about the benefit of using the JS function encodeURIComponent to encode each component of an http-get request when communicating with the server. After conducting some experiments, I found that the server (using PHP) is able to rece ...

Develop a simple application using the MEAN stack framework

I am new to Node.js and Express and I am interested in creating a basic AngularJS application. However, I am unsure of where to begin in terms of file organization. My desired file structure is as follows: - public ----- app ---------- components -------- ...