Is it possible to execute a SQLite query using ajax jQuery?

I am facing an issue with incorporating sqlite queries into the back getJSON response function in my phonegap application.

After trying to implement this code, I continuously encounter the following error:

INVALID_STATE_ERR: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.

This is the snippet of my code:

<script>
     document.addEventListener("deviceready", onDeviceReady, false);
     function onDeviceReady() {
        // establishing DB connection
         var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
         db.transaction(populateDB, errorCB, successCB);
    }

    function populateDB(tx) {

         tx.executeSql('DROP TABLE IF EXISTS buses');
         tx.executeSql('CREATE TABLE IF NOT EXISTS buses (bus_id INTEGER PRIMARY KEY,bus_no TEXT, bus_time TEXT,from_loc TEXT,to_loc TEXT,route TEXT)');
         $.getJSON('http://myegy.me/maryam/asem/api.php?table=trip', function(data) {
              $.each(data, function(key, val) {

                    tx.executeSql('INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES ("'+val['trip_number']+'","'+val['from_id']+'","'+val['to_id']+'","'+val['stop_station']+'")');
              });
            });

         tx.executeSql('DROP TABLE IF EXISTS bus_stations');
         tx.executeSql('CREATE TABLE IF NOT EXISTS bus_stations (id INTEGER PRIMARY KEY,station_name TEXT, station_description TEXT,station_lat TEXT,station_long TEXT)');
         $.getJSON('http://myegy.me/maryam/asem/api.php?table=station', function(data) {
              $.each(data, function(key, val) {

                    tx.executeSql('INSERT INTO bus_stations (station_name,station_lat,station_long) VALUES ("'+val['station_name']+'","'+val['latitude']+'","'+val['longitude']+'")');
              });
            });

    }

    </script>

The issue lies within these two lines:

 tx.executeSql('INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES ("'+val['trip_number']+'","'+val['from_id']+'","'+val['to_id']+'","'+val['stop_station']+'")');

and

tx.executeSql('INSERT INTO bus_stations (station_name,station_lat,station_long) VALUES ("'+val['station_name']+'","'+val['latitude']+'","'+val['longitude']+'")');

Answer №1

To improve efficiency, it's recommended to relocate the $.getJSON calls within the successCB function and pass the JSON data as a parameter to a function that handles data processing as a db.transaction.

function successCB() {
    $.getJSON('http://myegy.me/maryam/asem/api.php?table=trip', function (data) {
        setBuses(data);
    }
}

function setBuses(data) {
    this.db.transaction(
        function (tx) {
            var l = data.length;
            var sql = 'INSERT INTO buses (bus_no,from_loc,to_loc,route) VALUES (?,?,?,?)';
            var b;
            for (var i = 0; i < l; i++) {
                b = data[i];
                var params = [b.trip_number,b.from_id,b.to_id,b.stop_station];
                tx.executeSql(sql, params);
            }
        },
        errorCB,
        function () {}
    );
}

For further insights, consider reading the June 2012 article by Christophe Coenraets in Appliness titled 'Offline Data Synchronization' which can be found at .

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

What is the process for fetching and storing a binary file video in Flask's Blob?

I've been dealing with a video encoding issue for the past few days and I need some help. Objective: Capture a video from my laptop's webcam using a VueJS frontend application. Send this video to a Python Flask app on the backend via FormData u ...

Iterate through the JSON API call

Hello everyone, I am currently working with a JSON Request that is passed through a PHP function call. The request contains URLs along with the respective catids they belong to. I am looking for a way to iterate through this JSON data and create an associ ...

Issue with binding the expanded property in Angular Expansion Panel

Including Angular code within my HTML, I have Admin and User Main menu items available. <a id="adminId" (click)="sideNavLink($event)">Admin</a> <mat-accordion class="mat-accordion-setting"> <mat-expansi ...

Inserting server side markers asynchronously in ASP.Net - Mapping with Google Maps

I am facing a challenge with adding markers on my Google Map Canvas using AJAX while calling methods on the ASP.net server side. I attempted to use update panels and call Javascript functions on the server side using ScriptManager.RegisterClientScriptBlock ...

Utilizing ASP.NET MVC with Forms Authentication and AJAX to enable continuous polling without refreshing the authentication ticket's expiration

I am trying to find a method where I can prevent a Controller Action from resetting the Forms Authentication ticket sliding expiration. My goal is to continuously check the server for new information using ajax every x seconds, but this could potentially ...

JS Sorting and Transforming Data

Seeking to extract a single key value from a JSON response by filtering for a specific matching group. Here's what I have so far: let res = item.filter(it => it.groups.includes('unknown') && it.iccid); console.log(res.it.icci ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

Tips for extracting the right content without disrupting HTML tags by combining strip_tags and substr functions

Within my webpage, I display previews of posts sourced from RSS feeds. Each preview consists of approximately 300 characters. Upon clicking on an expand button, the #post-preview is then swapped out with the full #post. However, the format of the #post is ...

What is the process for running child_process when a user clicks on a view in an application

Just starting out with Node.js and utilizing express along with hogan or moustache templating for my views. I've successfully used the following code in my routing files, index.js as shown below: /* Test Shell Execute. */ router.get('/shell&apo ...

PHP, having difficulty assigning value to variable using $_POST

Having a minor frustrating issue... I am transmitting a form value to PHP using AJAX, and it appears to be functioning properly. Upon performing var_dump in PHP, I can see my values and even set a variable and echo it correctly. However, this line $prod_i ...

Sending Angular form data as an array format

Currently, I am sending a post request to the backend with only one input field. When I check the console, my request is displayed as "request." However, the backend actually requires the request to be formatted in an array such as ["request"]. ...

Guide to activating a reaction following an occurrence in a React component

I have started developing a React application that loads blog posts along with their associated comments. The challenge I am facing is how to trigger a refresh of the comments component and display the new comment immediately after it has been submitted. ...

Express did not receive a default engine specification or a file extension

I'm working on a project where I am using only HTML to render pages from my Express server. However, I keep encountering the following error message: No default engine was specified and no extension was provided. In my app.js file, I have specified ...

Learn how to update a form dynamically using the Ajax.BeginForm feature

I am currently working on updating a form within my application using Ajax.BeginForm. The update process is functioning correctly, however, upon executing the function in the controller, it redirects to a view with the controller function name displayed. ...

Use JavaScript to change the text of a hyperlink to @sometext

<li class="some-class one-more"><label>twitter:</label> <a href="https://twitter.com/sometext?s=09" target="_blank" rel="noreferrer noopener">https://twitter.com/sometext?s=09</a> < ...

use checkboxes to filter products in a Laravel application

I am currently developing a website with the Laravel framework, and I would like to implement checkboxes for filtering products by category. However, I am facing an issue where I can only display the selected category name in an alert message instead of fi ...

Updating data dynamically in pug front end using Axios call response

I am currently working on implementing a search form along with an endpoint to retrieve the results. Once I receive the response, I want to dynamically add a div element to my pug/jade file to notify the user whether an order has been found or not. Here i ...

Anticipated the start of an array but instead encountered the start of an object at line 1, column 2

I am currently utilizing retrofit 2 on my Android application to fetch data in JSON format from the server and use it as an object. The server-side is developed using NetBeans. However, I'm encountering the exception mentioned above when executing the ...

HTML: Body with a larger height than its actual content dimensions

My Chrome browser extension seems to have a body that is much taller than its actual content: https://i.sstatic.net/t44t6.pnghttps://i.sstatic.net/8WjzD.png Even though there are no other parent div elements, the height of the <div id='app'& ...

Exploring ways to utilize Vue data variables and methods within the configuration options of Tabulator

Utilizing tabulator in conjunction with vue using the following packages: tabulator-tables and vue-tabulator. In an attempt to implement a click event on the tabulator row, I am faced with the challenge of accessing vue data variables within the scope of ...