Save image into database - javascript

I am trying to set up database to store user image and name. I have put the code up on jsfiddle http://jsfiddle.net/Inkers/dZJnG/. When I run the code on my device I get a number of errors. Code here too:
HTML
<body onload="onDeviceReady()">
<h3>Enter name and picture</h3>
<div id= "userProfile">
<button onclick="takePhoto();">Capture Photo</button> <br>
<img style="display:none;width:100px;height:100px;" id="smallImage" src="" />
<p></p>
<input id="userName" type="text" placeholder="name">
<input id="saveProfile" type="button" value="Save" onClick="insertEntry();""location.href='Createtask.html'"> <br>
<input id="allUsers" type="button" value="All users" onClick="queryDB();"> <br>
</div>
JS
function init(){
document.addEventListener("deviceready", onDeviceReady, false);
}
var pictureSource; // picture source
var destinationType;
function onDeviceReady() {
var db = window.openDatabase("database", "1.0", "Profiles", 5000);
if(db) {
console.log('The database is working');
alert('The database is working');
db.transaction(createTable, insertEntry, errorCB, successCB); // only do stuff if db exists
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
else{
console.log('There is a problem');
}
}
function takePhoto(){
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
function onPhotoDataSuccess(imageData) {
console.log(imageData);
// Get image handle
var smallImage = document.getElementById('smallImage');
// Unhide image elements
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function createTable(tx) {
var sqlStr =('CREATE TABLE IF NONE EXISTS USERS(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, image BLOB)');
tx.executeSql(sqlStr,[],successCB, errorCB);
console.log("Users table created");
}
function insertEntry(tx){
var tmpName = document.getElementById("userName").value;
var tmpImage = document.getElementById("smallImage").src;
var sqlStr=('INSERT INTO USERS (name, image) VALUES (?,?)');
tx.executeSql = (sqlStr, [tmpName, tmpImage], onSqlSuccess, errorCB);
alert('record entered');
}
// Query the success callback
function onSqlSuccess(tx, res){
var len = results.rows.length;
console.log("USERS 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);
}
}
// Query the database
//
function queryDB() {
var sqlStr = ('SELECT * FROM USERS; ORDER BY id ASC');
database.transaction(function (tx){
tx.executeSql(sqlStr,[],onSqlSuccess, errorCB);
})
}
// Transaction error callback
//
function errorCB(err) {
console.log("Error processing SQL: "+err.code);
}
// Transaction success callback
//
function successCB() {
console.log('');
}

Related

Storing captured image into SQlite Database? (Cordova)

So far I have got the camera api working for my app, to which the camera is opened when a button is clicked and once the image is taken it is displayed on the page.
My next step is to store the image into my sqlite database within a table. Creating the database is no problem as I already have a couple of other tables used for other parts of the app which work fine, it's just finding out how to store the image into the database.
Can someone provide some assistance here?
Camera Function:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(function (imageUri) {
var lastPhotoContainer = document.getElementById("lastPhoto");
alert("Hot stuff!");
lastPhotoContainer.innerHTML = "<img src='" + imageUri + "' style='width: 75%;' />";
}, null, null);
};
}
HTML:
<div data-role="page" id="page7" data-theme="d">
<div data-role="header">
Sign ut
<h1>SoccerMeet</h1>
</div>
<div data-role="main" class="ui-content">
<input id="btnCamera" type="button" value="Camera photo" />
<p id="lastPhoto"></p>
</div>
<div data-role="footer">
<h2>© Gallery</h2>
</div>
</div>
UPDATED Script:
document.addEventListener("deviceready", onDeviceReady, false);
var db;
function onDeviceReady() {
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2 * 1024 * 1024);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Gallery (id INTEGER PRIMARY KEY, myImage BLOB)');
}, errorE, successS);
}
function successS() {
alert("Camera database ready!");
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(onSuccess, onFail, {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
};
}
function onSuccess(tx, imageData) {
alert("Camera test 1");
var image = document.getElementById("lastPhoto");
image.src = "data:image/jpeg;base64," + imageData;
base64imageData = imageData;
var _Query3 = ("INSERT INTO Gallery(myImage) values ('" + base64imageData + "')");
alert(_Query3);
tx.executeSql(_Query3);
}
/* function successCamera() {
navigator.notification.alert("Image has been stored", null, "Information", "ok");
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#page4" );
} */
function onFail(message) {
alert('Failed because: ' + message);
}
function errorE(err) {
alert("Error processing SQL: " + err.code);
}
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
document.getElementById("btnCamera").onclick = function() {
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
};
}
function onSuccess(imageData){
var image = document.getElementById("lastPhoto");
image.src = "data:image/jpeg;base64," + imageData;
//the imageData is a base64 representation of the image.
base64imageData=imageData;// this variable is a global variable and when ever asked for u can send it to SQL Operation class for storing.
}
function onFail(message) {
alert('Failed because: ' + message);
}

How to insert image in sqlite?

I am developing a cross platform application using cordova.
I need to insert image inside sqlite. I am getting lots of code for android but I find it difficult to do with javascript. I am getting err.code:5 when I run the following code in my iPhone.
document.addEventListener("deviceready", onDeviceReady, false);
var img;
var currentRow;
var b = new Blob();
function previewFile() {
// var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// var package_name = document.getElementById("pr").value;
reader.onloadend = function () {
// img = reader.result;
if(file.type.match('image.*'))
{
img = reader.result;
// ref.push({"image":image,"service":arr,"package_name":package_name});
}
else
{
alert("select an image file");
}
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
var image1 = encodeURI(img);
// var b = new Blob();
b = image1;
console.log(b);
console.log(image1);
//document.write('<img src="'+image+'"/>');
}
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER PRIMARY KEY AUTOINCREMENT, name,number,image BLOB)');
}
function insertDB(tx) {
tx.executeSql('INSERT INTO DEMO (name,number,image) VALUES ("' +document.getElementById("txtName").value
+'","'+document.getElementById("txtNumber").value+'","' +b+ '")');
}
function goInsert() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(insertDB, errorCB, successCB);
}
My html code:
<input type="file" onchange="previewFile()">
<button onclick="goInsert()">Insert</button>
How to do this. Can someone help me? Thanks in advance...
Convert your image (in memory) to a byte[] and then save it your sql db as varbinary(max).
Inserting blob into database will make your application slow as well as laggy, instead save the path of the selected picture into the database.
And when you want to upload the image to the server use
fileupload feature of cordova.
If you are getting image from server than download that image locally and save that path into the database
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
fileSystem.root.getFile(
"dummy.html", {create : true, exclusive : false},
function gotFileEntry(fileEntry)
{
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile)
{
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error)
{
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);

Having an Error processing SQL:0 PhoneGap SQL

I created an android app using html5 and phonegap and
I have a problem in inserting data into database..
this is my code
document.addEventListener("deviceready", onDeviceReady(), false);
var db;
function onDeviceReady(){
db = window.openDatabase("Libsys", "2.0", "LibraryDB", 200000); //will create database Dummy_DB or open it
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS Borrowinfo(id INTEGER PRIMARY KEY AUTOINCREMENT, IDno TEXT NOT NULL, Name TEXT NOT NULL, course TEXT NOT NULL, author TEXT NOT NULL, title TEXT NOT NULL, date_start TEXT NOT NULL, date_return TEXT NOT NULL)');
}
function queryDB(tx){
tx.executeSql('SELECT * FROM Borrowinfo', [], querySuccess, errorCB);
}
function querySuccess(tx,results){
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
$("#Lists").append("<li><a href='#'>"+row['Name']+" "+row['course']+"</a></li>");
}
$("#Lists").listview("refresh");
}
function SaveContacts(idno,fullname,course,author,title,dstart,dreturn){
//alert(""+idno+" "+fullname+"");
db.transaction(function(tx){
var idno = document.getElementById("idno").value;
var fullname = document.getElementById("names").value;
var course = document.getElementById("course").value;
var author = document.getElementById("author").value;
var title = document.getElementById("title").value;
var dstart = document.getElementById("dstart").value;
var dreturn = document.getElementById("dreturn").value;
tx.executeSql('INSERT INTO Borrowinfo(IDno,name,course,author,title,date_start,date_return) VALUES (?,?,?,?,?,?,?)', [idno,fullname,course,author,title,dstart,dreturn], querySuccess);
alert("Record Save!");
});
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
function successCB() {
db.transaction(queryDB,errorCB);
}
im having an error in the function querySuccess.. the error message is (undefined is not a function querySuccess)
Please, correct me and also help me to fixed the error...
thank you..

Retrieving value from database in Javascript

I am new to mobile application development with PhoneGap. I have created a form to add and show name, address and phone number of a student in SQLite database. But the problem is I don't know to retrieve and display the values in the text boxes.
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.4.1.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
}
function errorCB(tx, err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB() {
alert("success!");
}
function add(tx){
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name+"','"+address+"','"+phone+"')');
//tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}
function show(tx){
var name=document.getElementById('n');
tx.executeSql('SELECT * FROM DEMO WHERE (sname='"+name+"')');
document.f.n.value=name;
document.f.a.value=//??;
document.f.p.value=//??;
}
</script>
</head>
<body>
<form name="f" method="get" action="">
Name :<input type="text" id="n" size="10"></input><br>
Add :<input type="text" id="a" size="10"></input><br>
Phone :<input type="text" id="p" size="10"></input><br>
<input type="button" value="Add" onClick="add()">
<input type="button" value="Show" onClick="show()">
</form>
</body>
</html>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
alert("onDeviceReady called");
}
function populateDB(tx)
{
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (sname ,saddress ,sphone)');
var name=document.getElementById('n');
var address=document.getElementById('a');
var phone=document.getElementById('p');
tx.executeSql('INSERT INTO DEMO (sname ,saddress ,sphone) VALUES ('"+name.value+"','"+address.value+"','"+phone.value+"')');
}
function errorCB(tx, err)
{
alert("Error processing SQL: "+err);
}
// Transaction success callback
//
function successCB()
{
alert("success!");
}
function add()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
for more see link here
//show data from db
// Transaction success callback
function show()
{
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(queryDB, errorCB);
}
// Query the database
function queryDB(tx)
{
tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
}
// Query the success callback
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 + " sname = " + results.rows.item(i).sname + " saddress = " + results.rows.item(i).saddress);
}
}
// Transaction error callback
function errorCB(err)
{
console.log("Error processing SQL: "+err.code);
}
Inside your code for save call
db.transaction(populateDB, errorCB, successCB)
The function will return to
function populateDB(tx) {
var rr=escape(JSON.stringify(onedata));//here onedata is data you want to save I use json data here.
tx.executeSql('CREATE TABLE IF NOT EXISTS LeadInfo (data)');
tx.executeSql('INSERT INTO LeadInfo (data) VALUES ("'+ rr +'")');
alert("Insert")
}
function errorCB(tx, err) {
//alert("Error processing SQL Insert: "+err);
}
function successCB() {
// alert("success!");
}
For retrieval you can use following:
function queryDB(tx) {
tx.executeSql('SELECT * FROM LeadInfo', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
var tablereport="";
if (results != null && results.rows != null) {
for (var i = 0; i < results.rows.length; i++) {
var row =unescape(results.rows.item(i).data);
var obj = JSON.parse(row);
tablereport+='<a href="#"><span style="font-size:18px; font-weight:400; padding:10px 0px 10px 0px;">'+JSON.stringify(obj.lead_name)+'</span><span style="padding: 10px 16px;width: 100px;float: right;margin-top: -33px;margin-right: -80px;font-size:14px"></span><br>';
tablereport+='</li>';
tablereport+='</li>';
}
}
}
function errorCB(err) {
alert("Error processing SQL Retrive: "+err.code);
}

Check if DB exists and dropping DB in SQLlite IOS

I'm currently using phonegap to create and ios app.
While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.
I'm currently using the following creation code (from the phonegap wiki)
var mydb=false;
// initialise the database
initDB = function() {
try {
if (!window.openDatabase) {
alert('not supported');
} else {
var shortName = 'phonegap';
var version = '1.0';
var displayName = 'PhoneGap Test Database';
var maxSize = 65536; // in bytes
mydb = openDatabase(shortName, version, displayName, maxSize);
}
} catch(e) {
// Error handling code goes here.
if (e == INVALID_STATE_ERR) {
// Version number mismatch.
alert("Invalid database version.");
} else {
alert("Unknown error "+e+".");
}
return;
}
}
// db error handler - prevents the rest of the transaction going ahead on failure
errorHandler = function (transaction, error) {
// returns true to rollback the transaction
return true;
}
// null db data handler
nullDataHandler = function (transaction, results) { }
my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?
and secondly how can i drop all these databases that have been created.
transaction.executeSql('DROP DATABASE phonegap;');
does not seem to drop anything.
Thanks
Please try following code. it is not creating multiple database files, just cross verify by visiting location -/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0
This is sqlite3 example which cover create, insert, delete and drop queries on Table.
<!DOCTYPE html>
<html>
<body style="font: 75% Lucida Grande, Trebuchet MS">
<div id="content"></div>
<p id="log" style="color: gray"></p>
<script>
document.getElementById('content').innerHTML =
'<h4>Simple to do list</h4>'+
'<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
'<button onclick="newRecord()">new record</button>'+
'<button onclick="createTable()">create table</button>' +
'<button onclick="dropTable()">drop table</button>';
var db;
var log = document.getElementById('log');
db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
showRecords();
document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
function onError(tx, error) {
log.innerHTML += '<p>' + error.message + '</p>';
}
// select all records and display them
function showRecords() {
document.getElementById('results').innerHTML = '';
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
for (var i = 0, item = null; i &lt result.rows.length; i++) {
item = result.rows.item(i);
document.getElementById('results').innerHTML +=
'<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
item['id']+' '+item['text'] + '</span> x</li>';
}
});
});
}
function createTable() {
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
function(tx) { log.innerHTML = 'Table1Test created' },
onError);
});
}
// add record with random values
function newRecord() {
var num = Math.round(Math.random() * 10000); // random data
db.transaction(function(tx) {
tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
function(tx, result) {
log.innerHTML = 'record added';
showRecords();
},
onError);
});
}
function updateRecord(id, textEl) {
db.transaction(function(tx) {
tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
});
}
function deleteRecord(id) {
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
function(tx, result) { showRecords() },
onError);
});
}
// delete table from db
function dropTable() {
db.transaction(function(tx) {
tx.executeSql("DROP TABLE Table1Test", [],
function(tx) { showRecords() },
onError);
});
}
</script>
</body>
</html>
And about Droping Database...
Does not seem meaningful for an embedded database engine like SQLite. To create a new database, just do sqlite_open(). To drop a database, simply delete the file.
thanks,
Mayur
Manually deleting the SQLite database from the Library worked for me. Thanks for the precious tip.

Categories

Resources