could not open db , $ is not defined, Failed to load jquery - javascript

The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();

Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {

You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Related

Google Contacts to Dropdown List

I'm wondering if anyone can help with this. I am using the following code to pull my google contacts using OAuth and it's working fine so far, I get a response in the console log with XML from google that seems very complicated to read to be honest.
My end goal is to be able to populate a HTML form drop down list with the names of contacts from my address book, and attribute the phone number for that contact as a value for the chosen name.
Here's the code, please let me know if you have any ideas!
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
var clientId = 'ID_HERE';
var apiKey = 'KEY_HERE';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$(document).on("click",".googleContactsButton", function(){
gapi.client.setApiKey(apiKey);
window.setTimeout(authorize);
});
function authorize() {
gapi.auth.authorize(
{
client_id: clientId,
scope: scopes,
immediate: false
},
handleAuthorization
);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get(
"https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token="
+ authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
}
);
}
}
</script>
<script src="https://apis.google.com/js/client.js"></script>
<button class="googleContactsButton">Get my contacts</button>
</body>
</html>
EDIT
So, I've played around for a bit, and this is what I've got so far, which works fine, I get the results listed in as name on one line, then number on the next, then name, and so on..
Problems so far are as follows.
This only returns a limited number of contacts, I believe there's a limit on the response from the API which is 200 or something (I think), how would I go about having it display ALL the contacts that are there?
Also I'm still trying to get it to display in a select box format, allowing me to choose a name, and it would pass the number linked to that name to the form.
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>People API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<p>People API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'CLIENT ID.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/contacts.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listConnectionNames();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the display name if available for 10 connections.
*/
function listConnectionNames() {
gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 2000,
'personFields': 'names,phoneNumbers',
}).then(function(response) {
console.log(response)
var connections = response.result.connections;
appendPre('<select>');
if (connections.length > 0) {
for (i = 0; i < connections.length; i++) {
var person = connections[i];
if (person.names && person.names.length > 0) {
appendPre(person.names[0].displayName)
appendPre(person.phoneNumbers[0].value)
} else {
appendPre("No display name found for connection.");
}
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Accessing the Contacts
When you receive the response, the contacts are located under response.feed.entry, which is an array of contacts. Let's save those under var contacts = response.feed.entry. And as an example for what follows, let's take the contact Jimmy : var jimmy = contacts[0].
You have several attributes that you can access, like :
Email : jimmy.gd$email[0].address. ( there can be more emails )
Name : jimmy.title.$t.
Phone : jimmy.gd$phoneNumber[0].$t.
Address : jimmy.gd$postalAddress[0].$t.
Last update made : jimmy.updated.$t.
Warning : If the field is not set, it will be undefined. You have to first verify that it exists, like so :
// Standard way
var name;
if (jimmy.title != undefined) name = jimmy.title.$t
else name = "?? well too bad ??";
// The ninja way
var name = jimmy.title ? jimmy.title.$t : null;
Also
Change your get url to https://www.google.com/m8/feeds/contacts/default/**full**/... as you will get more information on your contacts.
Populating a drop-down
For simplicity, you could use a <select> tag and insert the contacts as <option> tags in it. Else, you can also use libraries like bootstrap that has cool drop-downs menus.
If your code still doesn't work...
Try this code :
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
function auth() {
var config = {
'client_id': 'OAUTH_CLIENT_ID',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?alt=json',
dataType: 'jsonp',
data: token
}).done(function(data) {
console.log(JSON.stringify(data));
});
}
</script>
</head>
<body>
<button onclick="auth();">GET CONTACTS FEED</button>
</body>
</html>
Source

Customize DocxJS to render local docx file

I just found a working docx to html converter using only javascript on github. The main code which converts docx to html is below. The issue is the page just has a button which on click or drag and choosing a word document, opens it as html. I want to specify a file location in the code so I can load it on the server for loading some documents from computer locally.
Code which converts docx to html and renders :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DocxJS Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="https://www.docxjs.com/js/build/latest.docxjs.min.js"></script>
</head>
<body>
<input id="inputFiles" type="file" name="files[]" multiple="false">
<div id="loaded-layout" style="width:100%;height:800px;"></div>
<script>
$(document).ready(function(){
var $inputFiles = $('#inputFiles');
$inputFiles.on('change', function (e) {
var files = e.target.files;
var docxJS = new DocxJS();
docxJS.parse(
files[0],
function () {
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
</script>
</body>
</html>
I tried changing var files = e.target.files; to var files = "C:/sda/path/to/docx"; but that didn't help.
I tried to change
var files = e.target.files;
to
var files = new Array(new File([""], "sample.docx"));
but it gives me OOXML parse error.
Update:
Lets say I have a file location variable in PHP and I wish to use that instead in the javascript code. How do I do it?
I also checked docx2html javascript code and here is the code for it:
<!DOCTYPE html>
<html>
<head>
<script src="index.js"></script>
<script>
function test(input){
require("docx2html")(input.files[0]).then(function(converted){
text.value=converted.toString()
})
}
</script>
</head>
<body>
<input type="file" style="position:absolute;top:0" onchange="test(this)">
<br/>
<br/>
<textarea id="text"></textarea>
</body>
</html>
Same issue need input.files[0] here as well
Update:
I am trying to use the method mentioned in the comments but encounter some errors:
var fil;
var getFileBlob = function (url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.addEventListener('load', function() {
cb(xhr.response);
});
xhr.send();
};
var blobToFile = function (blob, name) {
blob.lastModifiedDate = new Date();
blob.name = name;
return blob;
};
var getFileObject = function(filePathOrUrl, cb) {
getFileBlob(filePathOrUrl, function (blob) {
cb(blobToFile(blob, 'test.docx'));
});
};
getFileObject('demo.docx', function (fileObject) {
console.log(fileObject);
fil = fileObject;
});
The error primarily was “Cross origin requests are only supported for HTTP.” before I used https://calibre-ebook.com/downloads/demos/demo.docx instead of just demo.docx in above file path. This however gives another error:
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
which means chrome cannot load it. It needs to be working on a server. If someone can help providing a fix to make it work offline, let me know. The last method was asynchronous call.
In the browser, there is a sandbox policy.
It can not access files directly via Path.
Please access the file through drag & drop event or input file change event.

Javascript and HTML button to INSERT MySQL query

I can't use AJAX/PHP solution to upload some data to MySQL database by clicking html button so I created .js function.
upload.js:
function uploadLikes(post) {
// credentials
var pass = require("/home/user/auth.json");
var passString = JSON.stringify(pass);
var passJson = JSON.parse(passString);
var mysql = require("mysql");
var connection = mysql.createConnection({
host : passJson.bi_anr.host,
user : passJson.bi_anr.user,
password : passJson.bi_anr.password,
});
// source: https://stackoverflow.com/questions/5818312/mysql-with-node-js
connection.connect(function(err) {
// connected! (unless `err` is set)
});
var query = connection.query("INSERT INTO db.likes (max_hash, ts, likes) VALUES (?, unix_timestamp(now() ), 1 ) ;", post, function(err, result) {
// Neat!
});
//console.log(query.sql);
}
and according to THIS I created button with javascript execution:
HTML file:
<html>
<head>
<title>Like Button</title>
</head>
<body>
<script src="upload.js"></script>
<input id="clickMe" type="button" value="clickme" />
<script>
//- Using a function pointer:
document.getElementById("clickMe").onclick = uploadLikes('TEST');
</script>
</body>
</html>
but it does not work. JavaScript function is OK, because it works by executing it in terminal using node. Could you help me?

Why am I unable to get the contacts from my phone with Cordova's Contacts API?

I'm building a phone app with Phonegap well, actually with Steroids.js which is built on top of Phonegap. Right now, all I want to do is retrieve the list of contact names and numbers from my phone upon the launching of my app. I took a look at the Contacts api here and I thought I was using it correctly. Below is the script I have inside of my head tags. What have I done wrong?
<script src="http://localhost/cordova.js"></script>
<script src="components/steroids-js/steroids.js"></script>
<script src="javascripts/application.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
function onSuccess(contacts) {
alert('ons');
for (var i = 0; i < contacts.length; i++) {
//trying to display contacts in an alert message when I launch my app
alert("Display Name = " + contacts[i].displayName);
}
}
// onError: Failed to get the contacts
function onError(contactError) {
alert('onError!');
}
</script>
In your above code your cordova.js file is misplaced somewhere.
like
<script src="http://localhost/cordova.js"></script>
You need to copy that cordova.js file into assest/www/ folder (like assest/www/cordova.js)
so it becomes like below in your html file
<script src="cordova.js"></script>

Javascript using Phonegap Global Arrays not Working

I am creating a phonegap app to fetch contacts and save them in the database. I have created two empty global arrays at the top that will save the phone number and display name of a person which will be later stored in a database table. To check that the contacts are successfully saved in the array, I have created a test_data() function.
Now my problem is that the test_data() code is not working and no values are displayed in the log. Now if I move that code from test_data() function to onSuccess() it works fine. Here is the code. Isn't it the proper way to declare global a array in JS.
<!DOCTYPE html>
<html>
<head>
<title>Contact Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
var gcont = []; var gphon = [];
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var fields = ["displayName", "phoneNumbers"];
navigator.contacts.find(fields, onSuccess, onError, options);
test_data();
}
// onSuccess: Get a snapshot of the current contacts
//
function onSuccess(contacts) {
for(var index=0;index<contacts.length;index++){
gcont[index] = contacts[index].displayName;
gphon[index] = contacts[index].phoneNumbers[0].value;
}
}
function test_data(){
for (z=0;z<gcont.length;z++){
console.log(gcont[z]);}
}
// onError: Failed to get the contacts
//
function onError(contactError) {
alert('Error With Contacts!');
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Find Contacts</p>
</body>
</html>
The call to test_data() doesn't work in onDeviceReady() because the onSuccess callback to contacts.find is asynchronous and the arrays have not been populated when test_data() is executed.

Categories

Resources