Uncaught Error: NotFoundError: DOM IDBDatabase Exception 8 - javascript

I am having a strange issue with using indexeddb API in Javascript. The code below generate the error in the subject line:
var notesdisplay, db;
function initiate(){
notesdisplay = document.getElementById('notesdisplay');
var button = document.getElementById('save');
button.addEventListener('click', addobject);
var request = indexedDB.open('mydatabase');
request.addEventListener('error', showerror);
request.addEventListener('success', start);
request.addEventListener('upgradeneeded', createdb);
}
function showerror(e){
alert('Error: ' + e.code + ' ' + e.message);
}
function start(e){
db = e.target.result;
show();
}
function createdb(e){
var datababase = e.target.result;
var mystore = datababase.createObjectStore('notesTable', {keyPath: 'id'});
mystore.createIndex('searchNotes', 'id', {unique: false});
}
function addobject(){
var title = document.getElementById('notesbox').value;
var mytransaction = db.transaction(['notesTable'], "readwrite");
var mystore = mytransaction.objectStore('notesTable');
var request = mystore.add({id: title});
request.addEventListener('success', show);
document.getElementById('notesbox').value = '';
}
function show(){
notesdisplay.innerHTML = '';
var mytransaction = db.transaction(['notesTable']);
var mystore = mytransaction.objectStore('notesTable');
var myindex = mystore.index('searchNotes');
var newcursor = myindex.openCursor(null, "prev");
newcursor.addEventListener('success', showlist);
}
function showlist(e){
var cursor = e.target.result;
if(cursor){
notesdisplay.innerHTML += '<div>' + cursor.value.id + ' - ' + ' <input type="button" onclick="removeobject(\'' + cursor.value.id + '\')" value="remove"></div>';
cursor.continue();
}
}
function removeobject(keyword){
if(confirm('Are you sure?')){
var mytransaction = db.transaction(['notesTable'], "readwrite");
var mystore = mytransaction.objectStore('notesTable');
var request = mystore.delete(keyword);
request.addEventListener('success', show);
}
}
addEventListener('load', initiate);
When I run this from within Chrome I get the error in the subject line. However, when I run this from Firefox a different error is generated (probably on the same lines).
--
[19:13:54.870] TypeError: db is undefined
Although I am fairly new to Javascript, in my mind the variable db is defined within the start function as here:
function start(e){ db = e.target.result; show(); }
This program is a simplified version of an example I had obtained from a book. This only has one key / value pair.
Any suggestions / pointers as to what could be the issue would be much appreciated.
Many thanks,
vnayak

Your request to open a database connection could be getting blocked. Try adding the following to your initiate function
request.addEventListener('blocked', function() { console.log('blocked'); });

Related

JavaScript Web Resource issue: getGrid() suddenly started failing

I have a few different JavaScript web resources that use the getGrid(), all of which started failing this week after I enabled the 2020 Wave 1 Updates in D365. The error message shows:
"Error occurred :TypeError: Unable to get property 'getGrid' of undefined or null reference"
Here is my code:
function GetTotalResourceCount(executionContext) {
console.log("function started");
var execContext = executionContext;
var formContext = executionContext.getFormContext();
var resourceyescount = 0;
try {
var gridCtx = formContext._gridControl;
var grid = gridCtx.getGrid();
var allRows = grid.getRows();
var duplicatesFound = 0;
//loop through rows and get the attribute collection
allRows.forEach(function (row, rowIndex) {
var thisRow = row.getData().entity;
var thisRowId = thisRow.getId();
var thisResource = "";
var thisResourceName = "";
var thisResourceID = "";
console.log("this row id=" + thisRowId);
var thisAttributeColl = row.getData().entity.attributes;
thisAttributeColl.forEach(function (thisAttribute, attrIndex) {
var msg = "";
if (thisAttribute.getName() == "new_resource") {
thisResource = thisAttribute.getValue();
thisResourceID = thisResource[0].id;
thisResourceName = thisResource[0].name;
console.log("this resource name=" + thisResourceName)
}
});
var allRows2 = formContext.getGrid().getRows();
//loop through rows and get the attribute collection
allRows2.forEach(function (row, rowIndex) {
var thatRow = row.getData().entity;
var thatRowId = thatRow.getId();
var thatAttributeColl = row.getData().entity.attributes;
var thatResource = "";
var thatResourceName = "";
var thatResourceID = "";
thatAttributeColl.forEach(function (thatAttribute, attrIndex) {
if (thatAttribute.getName() == "new_resource") {
thatResource = thatAttribute.getValue();
thatResourceID = thatResource[0].id;
thatResourceName = thatResource[0].name;
if (thatResourceID == thisResourceID && thatRowId != thisRowId) {
duplicatesFound++;
var msg = "Duplicate resource " + thatResource;
console.log("duplicates found= " + duplicatesFound);
}
}
});
});
});
if (duplicatesFound > 0) {
console.log("duplicate found");
Xrm.Page.getAttribute("new_showduplicateerror").setValue(true);
Xrm.Page.getControl("new_showduplicateerror").setVisible(true);
Xrm.Page.getControl("new_showduplicateerror").setNotification("A duplicate resource was found. Please remove this before saving.");
} else {
Xrm.Page.getAttribute("new_showduplicateerror").setValue(false);
Xrm.Page.getControl("new_showduplicateerror").setVisible(false);
Xrm.Page.getControl("new_showduplicateerror").clearNotification();
}
} catch (err) {
console.log('Error occurred :' + err)
}
}
Here is a separate web resource that triggers the function:
function TriggerSalesQDResourceCount(executionContext){
var formContext = executionContext.getFormContext();
formContext.getControl("s_qd").addOnLoad(GetTotalResourceCount);
}
Any ideas how I can fix this? Is this a known issue with the new D365 wave 1 update?
Thanks!
This is the problem with unsupported (undocumented) code usage, which will break in future updates.
Unsupported:
var gridCtx = formContext._gridControl;
You have to switch to these supported methods.
function doSomething(executionContext) {
var formContext = executionContext.getFormContext(); // get the form Context
var gridContext = formContext.getControl("Contacts"); // get the grid context
// Perform operations on the subgrid
var grid = gridContext.getGrid();
}
References:
Client API grid context
Grid (Client API reference)

mediawiki api can not display the results from array

Hello you wonderful people, I am trying to build JavaScript file to extract information from Wikipedia based on search value in the input field and then display the results with the title like link so the user can click the link and read about it. So far I am getting the requested information in(JSON)format from Mediawiki(Wikipedia) but I can't get it to display on the page. I think I have an error code after the JavaScript array.
I'm new at JavaScript any help, or hint will be appreciated.
Sorry my script is messy but I am experimenting a lot with it.
Thanks.
var httpRequest = false ;
var wikiReport;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
} catch (requestError) {
return false;
}
return httpRequest;
}
function getWiki(evt) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
var search = document.getElementsByTagName("input")[0].value;//("search").value;
if (!httpRequest) {
httpRequest = getRequestObject();
}
httpRequest.abort();
httpRequest.open("GET", "https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=" + search , true);//("get", "StockCheck.php?t=" + entry, true);
//httpRequest.send();
httpRequest.send();
httpRequest.onreadystatechange = displayData;
}
function displayData() {
if(httpRequest.readyState === 4 && httpRequest.status === 200) {
wikiReport = JSON.parse(httpRequest.responseText);//for sunchronus request
//wikiReport = httpRequest.responseText;//for asynchronus request and response
//var wikiReport = httpRequest.responseXML;//processing XML data
var info = wikiReport.query;
var articleWiki = document.getElementsByTagName("article")[0];//creating the div array for displaying the results
var articleW = document.getElementById("results")[0];
for(var i = 0; i < info.length; i++)
{
var testDiv = document.createElement("results");
testDiv.append("<p><a href='https://en.wikipedia.org/?curid=" + query.pages[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
var newDiv = document.createElement("div");
var head = document.createDocumentFragment();
var newP1 = document.createElement("p");
var newP2 = document.createElement("p");
var newA = document.createElement("a");
head.appendChild(newP1);
newA.innerHTML = info[i].pages;
newA.setAttribute("href", info[i].pages);
newP1.appendChild(newA);
newP1.className = "head";
newP2.innerHTML = info[i].title;
newP2.className = "url";
newDiv.appendChild(head);
newDiv.appendChild(newP2);
articleWiki.appendChild(newDiv);
}
}
}
//
function createEventListener(){
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener) {
form.addEventListener("submit", getWiki, false);
} else if (form.attachEvent) {
form.attachEvent("onsubmit", getWiki);
}
}
//createEventListener when the page load
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
Mediawiki api link
https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=3&generator=search&origin=*&gsrsearch=
You are wrong some points.
1)
var articleW = document.getElementById("results")[0];
This is wrong. This will return a element is a reference to an Element object, or null if an element with the specified ID is not in the document. Doc is here (https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
The correct answer should be :
var articleW = document.getElementById("results");
2)
var info = wikiReport.query;
for(var i = 0; i < info.length; i++) {}
The info is object . it is not array , you can't for-loop to get child value.
wikiReport.query is not correct wiki data. The correct data should be wikiReport.query.pages. And use for-in-loop to get child element
The correct answer:
var pages = wikiReport.query.pages
for(var key in pages) {
var el = pages[key];
}
3) This is incorrect too
testDiv.appendChild("<p><a href='https://en.wikipedia.org/?curid=" + query.info[i].pageid + "' target='_blank'>" + query.info[i].title + "</a></p>");
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. You are using the method to adds a string . This will cause error. Change it to node element or use append method instead
I have created a sample test.You can check it at this link below https://codepen.io/anon/pen/XRjOQQ?editors=1011

Send object id from success function to another function in parse.com

I have a problem on parse.com in which i to take the id of an type and pass it to another function which uploads an image. Then take the type.id among with the image and post it to another function which saves the data to a class.
This is what i've tried until now without success.
--OnClick code
$('#submitId').on("click", function(e, f) {
e.preventDefault();
typeSave(typeid1);
//var objnew1 = typeSave();
console.log("inside onclick " + type2);
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
//typeSave();
type2 = typeid1;
saveJobApp(parseFile, type2);
console.log("inside save onclick " + type2);
},
function(error) {
alert("error");
}
);
});
-- Type Code
var type;
var typeid1;
var type2;
function typeSave() {
var type = new Parse.Object("type");
var user = new Parse.Object("magazia");
//var bID = objbID;
//user.id = bID;
var cafebar = document.getElementById('cafe_bar').checked;
if (cafebar) {
var valueCafebar = true;
} else {
var valueCafebar = false;
}
var club = document.getElementById('club').checked;
if (club) {
var valueClub = true;
} else {
var valueClub = false;
}
var restaurant = document.getElementById('restaurant').checked;
if (restaurant) {
var valueRestaurant = true;
} else {
var valueRestaurant = false;
}
var pistes = document.getElementById('pistes').checked;
if (pistes) {
var valuePistes = true;
} else {
var valuePistes = false;
}
type.set("cafebar", valueCafebar);
type.set("club", valueClub);
type.set("restaurant", valueRestaurant);
type.set("pistes", valuePistes);
type.save(null, {
success: function(type) {
//saveJobApp(type.id);
var typeid1 = type.id;
console.log("inside type save " + typeid1);
//return ;
},
error: function(type, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
-- Send Data to parse.com class code
function saveJobApp(objParseFile, type2) {
var jobApplication = new Parse.Object("magazia");
var email = document.getElementById('email').value;
var name = document.getElementById('name').value;
var description = document.getElementById('description').value;
var website = document.getElementById('website').value;
var phone = document.getElementById('phone').value;
var address = document.getElementById('address').value;
var latlon = document.getElementById('latlon').value;
var area = document.getElementById('area').value;
var value = latlon;
value = value.replace(/[\(\)]/g, '').split(', ');
console.log("inside saveJobApp " + type2);
var x = parseFloat(value[0]);
var y = parseFloat(value[1]);
var point = new Parse.GeoPoint(x, y);
jobApplication.set("image", objParseFile);
jobApplication.set("email", email);
jobApplication.set("phone", phone);
jobApplication.set("address", address);
jobApplication.set("name", name);
jobApplication.set("website", website);
jobApplication.set("description", description);
jobApplication.set("area", area);
jobApplication.set("latlon", point);
jobApplication.set("typeID", type2);
jobApplication.save(null, {
success: function(gameScore) {
// typeSave(jobApplication.id);
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
So resuming i am trying when i click the button to first run the typesave() function, after when it posts the type on the type class in parse, to take to type.id from the success function and send it to the parseFile.save().then
and then to send the objectFile and the type2 (which is the type.id) it in saveJobApp and them to save it in class magazia
What i get from the console.logs is this
Which means that my code post to the type class and takes the type.id
but it doesnt send it to the magazia class via the parsefile save.
Any idea of what am i missing?
I noticed your mistake is not about the functions but about trying to pass the type.id as a string and not as a function in the saveJobApp function.
if you try making it like this
function saveJobApp(objParseFile , objtype) {
var jobApplication = new Parse.Object("magazia");
var type = new Parse.Object("type");
type.id = objtype;
jobApplication.set("typeID", type);
I think it will work.
And also update the onclick and the ParseFile save code to this
$('#submitId').on("click", function(e) {
typeSave();
});
function PhotoUpload(objtype){
var fileUploadControl = $("#profilePhotoFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
parseFile.save().then(
function() {
saveJobApp(parseFile, objtype);
},
function(error) {
alert("error");
}
);
}
And the success function in typeSave()
should be something like this
type.save(null, {
success: function(type) {
PhotoUpload(type.id);
},
Hope this helps :)

app.open not responding if called from inside onclick()

Working on a script for InDesign I found this problem : if I call app.open() from inside button.onclick() it stops and nothing happens.
Since I'm a beginner with Javascript I'm probably doing something wrong. But if not, how do I fix? I can not find an alternative.
Please, only pure Javascript.
Thanks in advance.
Here the working code :
var book_info;
if (app.books.length != 1) {
var theFile = File.openDialog ("Select the book file to open...");
get_data(theFile);
alert(book_info.filePath + "\r" + book_info.name);
}
book_info.close();
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}
and here the one not working :
var book_info;
var w1 = new Window ("dialog", "TEST");
w1.minimumSize.height = 50;
w1.minimumSize.width = 50;
var p1 = w1.add ("panel");
sel_button = p1.add ("button", undefined, "Select book");
var g1 = w1.add ("group");
g1.add("button", undefined, "Cancel");
g1.add("button", undefined, "OK");
sel_button.onClick = function(){
var theFile = File.openDialog ("Select the book file to open...");
get_data(theFile);
alert(book_info.filePath + "\r" + book_info.name);
book_info.close();
};
w1.show();
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}
There is an alternative answer at app.open not responding if called from inside onclick()
It also suggested the use of 'palette' window instead of modal dialogue
Try this:
var book_info;
var theFile;
var getData;
var w1 = new Window ("dialog", "TEST");
w1.minimumSize.height = 50;
w1.minimumSize.width = 50;
var p1 = w1.add ("panel");
sel_button = p1.add ("button", undefined, "Open a book");
var g1 = w1.add ("group");
g1.add("button", undefined, "Cancel");
g1.add("button", undefined, "OK");
sel_button.onClick = function(){
theFile = File.openDialog ("Select the book file to open...");
getData =1;
w1.close(1);
};
w1.show()
if ( getData ==1) {
if ( theFile ) {
get_data(theFile);
}
}
function get_data(data) {
app.open(data);
book_info = app.activeBook;
alert("INSIDE FUNCTION" + book_info.filePath + "\r" + book_info.name);
return data;
}

Getting a "setVersion" is not a function error when using indexedDB

I tried to use following code to test the performance of IndexedDB.
The code is modified from http://www.html5rocks.com/en/tutorials/indexeddb/todo/ ,
It works well in chrome, but fails in Firefox 10, saying "db.setVersion is not a function".
I want to know how can I modify the code to make it work in firefox?
var count=0;
var MAX=10;
var times=3;
var allTime;
var stime;
var etime;
var html5rocks = {};
var indexedDB = window.indexedDB || window.webkitIndexedDB ||
window.mozIndexedDB;
if ('webkitIndexedDB' in window) {
window.IDBTransaction = window.webkitIDBTransaction;
window.IDBKeyRange = window.webkitIDBKeyRange;
}
html5rocks.indexedDB = {};
html5rocks.indexedDB.db = null;
html5rocks.indexedDB.onerror = function(e) {
//console.log(e);
alert("Why didn't you allow my web app to use IndexedDB?!");
};
html5rocks.indexedDB.open = function(type) {
var request = indexedDB.open("todos");
request.onsuccess = function(e) {
var v = "1.20";
html5rocks.indexedDB.db = e.target.result;
var db = html5rocks.indexedDB.db;
// We can only create Object stores in a setVersion transaction;
if (v!= db.version) {
var setVrequest = db.setVersion(v);
// onsuccess is the only place we can create Object Stores
setVrequest.onerror = html5rocks.indexedDB.onerror;
setVrequest.onsuccess = function(e) {
if(db.objectStoreNames.contains("todo")) {
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "number"});
addTest();
};
}
else addTest();
};
request.onerror = html5rocks.indexedDB.onerror;
}
html5rocks.indexedDB.addTodo = function(todoText,num) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data = {
"text": todoText,
"number": num
};
var request = store.put(data);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
getTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.getTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.get(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
delTest();
}
};
request.onerror = function(e) {
console.log("Error getting: ", e);
};
};
html5rocks.indexedDB.deleteTodo = function(id) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e) {
count++;
if(count>=times*MAX)
{
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf())/times)+"<br/>";
allTime=0;stime=new Date;count=0;
dataTest();
}
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.addData = function(d) {
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var data={
"text":d,
"number":1
};
var request = store.put(data);
request.onsuccess = function(e) {
etime=new Date;
var t=document.getElementById('result').innerHTML;
document.getElementById('result').innerHTML=t+((etime.valueOf()-stime.valueOf()))+"<br/>";
};
request.onerror = function(e) {
console.log("Error Adding: ", e);
};
};
function addTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.addTodo(' ',i);
}
function getTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.getTodo(Math.round(Math.random()*(MAX*times-1)+1));
}
function delTest() {
for(i=1;i<=times*MAX;i++)
html5rocks.indexedDB.deleteTodo(i);
}
function dataTest() {
data=' ';
for(i=1;i<=21;i++)
data=data+data;
stime=new Date
html5rocks.indexedDB.addData(data);
}
function init() {
stime=new Date;
allTime=0;
html5rocks.indexedDB.open();
}
The spec is not finalized. This is currently shipped as the property mozIndexedDB in Gecko and webkitIndexedDB in Chrome until the standard is finalized. So you have to write for moz also. Now this code is only for webkit.
https://developer.mozilla.org/en/IndexedDB
setVersion() is Deprecated
The new way is to define the version in the IDBDatabase.open() method
firefox from version 10.0 implements open() with the new specification in which an indexeddb database IDBDatabase version is set as the second parameter of the open() method
example
var v = "1.20";
var request = indexedDB.open("todos", v);
html5 indexeddb javascript
The problem here is not the one chosen as the correct answer.
The problem is that the IndexedDB examples on HTML5Rocks were written to the pre-January IndexeDB spec. The working group has since published a breaking change going from the setVersion API to the new onupgradedneeded style.
Here, Firefox is technically correct to fail. Star this issue if you want to see Chrome do the same.

Categories

Resources