In a JQuery JSON Cordova issue on Stack Overflow someone had trouble populating a sqlite database when using the JQuery AJAX and JSON APIs due to a subtle misunderstanding of how the Web SQLite API works. This post is written to explain how this can go wrong and how to follow the SQLite API correctly. This post assumes a very basic understanding of how the Web SQL API or Cordova-sqlite-storage API works.
In general, once a database is open it should be possible to populate it using the following form:
But the following code will NOT work:
db.executeSql is sometimes used to execute a sql statement without the overhead of the transaction process.
$.ajax is an asynchronous call, the database transaction is finished before the
success callback is triggered.
Doing it right
Create a Cordova project with the plugins
As a result, you should have a Cordova project that has logging enabled, Cordova-sqlite-storage plugin installed, and multi-domain “whitelisting” enabled.
UPDATED: Content-Security-Policy meta tag
It took me 2-3 hours of searching, trial, and error last week to discover this one. As of this writing, the Cordova default project template has a limited
Content-Security-Policy setting in the meta tag. This will block queries to most domains.
Content-Security-Policy meta tag in
www/index.html according to the accepted answer:
WARNING: This is extremely insecure and should only be considered for a limited test application. Please follow the official documentation to configure the
Content-Security-Policy meta tag correctly.
- Download a recent version of jquery.js (such as
1.11.3as of this writing) from http://jquery.com/download/, either compressed or uncompressed
- Install it in the
- Add the
www/index.htmlto load the installed version of
Add simple AJAX query for JSON data
Add the following code to the
onDeviceReady function in
Build and run
Use the Cordova CLI commands to add the desired platform, such as Android or iOS, and run your app (on the emulator or on a device). For example:
IMPORTANT NOTE: If you modify
config.xml or any files in the
www tree (such as
index.js) please run the following command to refresh the Android, iOS, and/or Windows project(s) before running again:
Add SQLite queries
Add the following code before the
It is recommended to remove (or comment out) the alert from the
success callback. Add the following code to the
For review, you should have the following code in the the
onDeviceReady function in
Build and run again
Then use the
cordova run command, for example:
A project with the program working is published at @brodybits/cordova-sqlite-with-jquery-ajax-api-demo.