I am using indexdb as it supports all browser. I have successfully added data and got data from indexdb but I want to use where clause condition. Like I have Product Name, Pathogen, Disease,Route so I want to get data where Product Name let's say is Ali and Disease is Skin. They way I have got from different sites what it does it show all the record with starting and end the value provided in the two input fields.
Here is my code which I am using.
<!doctype html>
<html>
<head>
</head>
<body>
<script>
var db;
function indexedDBOk() {
return "indexedDB" in window;
}
document.addEventListener("DOMContentLoaded", function() {
//No support? Go in the corner and pout.
if(!indexedDBOk) return;
var openRequest = indexedDB.open("products",1);
//var openRequest = indexedDB.open("idarticle_people5",1);
openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("products")) {
var os = thisDB.createObjectStore("products", {autoIncrement:true});
//I want to get by name later
os.createIndex("name", "name", {unique:false});
//I want email to be unique
os.createIndex("pathogen", "pathogen", {unique:false});
os.createIndex("disease", "disease", {unique:false});
os.createIndex("route", "route", {unique:false});
}
}
openRequest.onsuccess = function(e) {
db = e.target.result;
//Listen for add clicks
document.querySelector("#addButton").addEventListener("click", addPerson, false);
//Listen for get clicks
document.querySelector("#getButton").addEventListener("click", getPerson, false);
}
openRequest.onerror = function(e) {
//Do something for the error
}
},false);
function addPerson(e) {
var name = document.querySelector("#name").value;
var pathogen = document.querySelector("#pathogen").value;
var disease = document.querySelector("#disease").value;
var route = document.querySelector("#route").value;
console.log("About to add "+name+"/"+pathogen);
//Get a transaction
//default for OS list is all, default for type is read
var transaction = db.transaction(["products"],"readwrite");
//Ask for the objectStore
var store = transaction.objectStore("products");
//Define a person
var person = {
name:name,
pathogen:pathogen,
disease:disease,
route:route
}
//Perform the add
var request = store.add(person);
request.onerror = function(e) {
alert("Sorry, that email address already exists.");
console.log("Error",e.target.error.name);
console.dir(e.target);
//some type of error handler
}
request.onsuccess = function(e) {
console.log("Woot! Did it");
}
}
function getPerson(e) {
var name = document.querySelector("#nameSearch").value;
var endname = document.querySelector("#diseaseSearch").value;
if(name == "" && endname == "") return;
var transaction = db.transaction(["products"],"readonly");
var store = transaction.objectStore("products");
var index = store.index("name");
//Make the range depending on what type we are doing
var range;
if(name != "" && endname != "") {
range = IDBKeyRange.bound(name, endname);
} else if(name == "") {
range = IDBKeyRange.upperBound(endname);
} else {
range = IDBKeyRange.lowerBound(name);
}
var s = "";
index.openCursor(range).onsuccess = function(e) {
var cursor = e.target.result;
if(cursor) {
s += "<h2>Key "+cursor.key+"</h2><p>";
for(var field in cursor.value) {
s+= field+"="+cursor.value[field]+"<br/>";
}
s+="</p>";
cursor.continue();
}
document.querySelector("#status").innerHTML = s;
}
}
</script>
<input type="text" id="name" placeholder="Name"><br/>
<input type="text" id="pathogen" placeholder="Pathogen"><br/>
<input type="text" id="disease" placeholder="Disease"><br/>
<input type="text" id="route" placeholder="Route"><br/>
<button id="addButton">Add Data</button>
<p/>
<input type="text" id="nameSearch" placeholder="Name"><br/>
<input type="text" id="diseaseSearch" placeholder="Disease"><br/>
<button id="getButton">Get By Name</button>
<p/>
<div id="status"></div>
</body>
</html>
You can try the following procedure with three parameters:
databaseid
tableid - storage name
callback - function, which returns array of selected data
cond - conditional function. returns true for ok records, and false for others.
Here is the code:
function selectFromTable (databaseid, tableid, cb, cond) {
var request = window.indexedDB.open(databaseid);
request.onsuccess = function(event) {
var res = [];
var ixdb = event.target.result;
var tx = ixdb.transaction([tableid]);
var store = tx.objectStore(tableid);
var cur = store.openCursor();
cur.onblocked = function(event) {
}
cur.onerror = function(event) {
}
cur.onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cond(cursor.value) ) res.push(cursor.value);
cursor.continue();
} else {
ixdb.close();
cb(res);
}
}
}
Try using a browser database API adapter and read about its usage from its wiki page.
You need to include all 3 JS files to get started.
Related
I created a To-Do List with Javascript, HTML and IndexedDB to store the Items in the database so that when I refresh the Browser the items won't get deleted. I also want to add the Date to the Items, but when I press the button to add an Item, the Date always becomes the same as the other items, but that's not how it should work:
I want that the date is always as I choose it to be for every Item.
It's the first time i ask a question here, so i hope it's not completely wrong how I do it.
Here is the whole code, i think the problem lays in the renderTodo(row)-function but I am not sure:
<!DOCTYPE html>
<html>
<head>
<title>ToDo-List IndexedDB</title>
<script type="text/javascript">
var html5rocks = {};
window.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);
};
html5rocks.indexedDB.open = function()
{
var version = 1;
var request = indexedDB.open("todos", version);
// We can only create Object stores in a versionchange transaction.
request.onupgradeneeded = function(e)
{
var db = e.target.result;
// A versionchange transaction is started automatically.
e.target.transaction.onerror = html5rocks.indexedDB.onerror;
if(db.objectStoreNames.contains("todo"))
{
db.deleteObjectStore("todo");
}
var store = db.createObjectStore("todo",
{keyPath: "timeStamp"});
};
request.onsuccess = function(e)
{
html5rocks.indexedDB.db = e.target.result;
html5rocks.indexedDB.getAllTodoItems();
};
request.onerror = html5rocks.indexedDB.onerror;
};
html5rocks.indexedDB.addTodo = function(todoText)
{
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var data =
{
"text": todoText,
"timeStamp": new Date().getTime()
};
var request = store.put(data);
request.onsuccess = function(e)
{
html5rocks.indexedDB.getAllTodoItems();
};
request.onerror = function(e)
{
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.deleteTodo = function(id)
{
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
var request = store.delete(id);
request.onsuccess = function(e)
{
html5rocks.indexedDB.getAllTodoItems();
};
request.onerror = function(e)
{
console.log("Error Adding: ", e);
};
};
html5rocks.indexedDB.getAllTodoItems = function()
{
var todos = document.getElementById("list");
todos.innerHTML = "";
var db = html5rocks.indexedDB.db;
var trans = db.transaction(["todo"], "readwrite");
var store = trans.objectStore("todo");
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e)
{
var result = e.target.result;
if(!!result == false)
return;
renderTodo(result.value);
result.continue();
};
cursorRequest.onerror = html5rocks.indexedDB.onerror;
};
function renderTodo(row)
{
const dt = getDatePickerDate('date');
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
if(row.text.trim() == "")
{
document.getElementById("ausgabe").innerHTML = "<br/><br/> Have to enter a task!";
}
else
{
document.getElementById("ausgabe").innerHTML = "";
var input_date = " " + dt.toLocaleDateString([], options) + ": " + row.text;
var list = document.getElementById("list");
var container = document.createElement("container");
var button = document.createElement("button");
button.type = "button";
button.innerText = "X";
var a = document.createElement("a");
button.addEventListener("click", function()
{
html5rocks.indexedDB.deleteTodo(row.timeStamp);
}, false);
container.appendChild(document.createElement("br"));
container.appendChild(document.createElement("br"));
container.appendChild(button);
container.appendChild(document.createTextNode(input_date));
container.appendChild(document.createElement("br"));
list.appendChild(container);
}
}
function getDatePickerDate(elementId)
{
const value = document.getElementById(elementId).value
const [year, month, day] = value.split('-');
return new Date(year, month - 1, day);
}
function addTodo()
{
var todo = document.getElementById("todo");
html5rocks.indexedDB.addTodo(todo.value);
todo.value = "";
}
function init()
{
html5rocks.indexedDB.open();
}
window.addEventListener("DOMContentLoaded", init, false);
</script>
</head>
<body style="background-color:#647e7f">
<h1 style="position:absolute;top:10px;left:10px;">ToDo Liste </h1>
<br /><br /><br /> <br /><br /> <br /><br /><h2>Activity:</h2><br /><br />
<textarea id="todo" name="text_input" rows="10" cols="50">
</textarea>
<br />
<input type="date" id="date">
<input type="button" value="add" id = "speichern" onclick="addTodo()" />
<br />
<p id = "ausgabe" ></p>
<container id = "list" ></container>
</body>
</html>
It is because your code is synchronous. Each addTodo happens sequentially and synchronous
To get different dates, Make functions async, await each transaction to database (it will take time)
html5rocks.indexedDB.addTodo = async function(...
...
var request = await store.put(data);
As others before I used yql to get data from a website. The website is in xml format.
I am doing this to build a web data connector in Tableau to connect to xmldata and I got my code from here: https://github.com/tableau/webdataconnector/blob/v1.1.0/Examples/xmlConnector.html
As recommended on here: YQL: html table is no longer supported I tried htmlstring and added the reference to the community environment.
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
However, I still got the message: Html table no longer supported.
As I don't know much about yql, I tried to work with xmlHttpRequestinstead, but Tableau ended up processing the request for ages and nothing happened.
Here my attempt to find another solution and avoid the yql thingy:
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//INSTEAD OF THIS:
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//USE NOT YQL BUT XMLHTTPREQUEST:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
Does anyone have an idea how to get YQL work or comment on my approach trying to avoid it?
Thank you very much!
For reference, if there is any Tableau user that wants to test it on Tableau, here is my full code:
<html>
<head>
<title>XML Connector</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://connectors.tableau.com/libs/tableauwdc-1.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {
var myConnector = tableau.makeConnector();
myConnector.init = function () {
tableau.connectionName = 'XML data';
tableau.initCallback();
};
myConnector.getColumnHeaders = function() {
_retrieveXmlData(function (tableData) {
var headers = tableData.headers;
var fieldNames = [];
var fieldTypes = [];
for (var fieldName in headers) {
if (headers.hasOwnProperty(fieldName)) {
fieldNames.push(fieldName);
fieldTypes.push(headers[fieldName]);
}
}
tableau.headersCallback(fieldNames, fieldTypes); // tell tableau about the fields and their types
});
}
myConnector.getTableData = function (lastRecordToken) {
_retrieveXmlData(function (tableData) {
var rowData = tableData.rowData;
tableau.dataCallback(rowData, rowData.length.toString(), false);
});
};
tableau.registerConnector(myConnector);
})();
function _retrieveXmlData(retrieveDataCallback) {
if (!window.cachedTableData) {
var conData = JSON.parse(tableau.connectionData);
var xmlString = conData.xmlString;
if (conData.xmlUrl) {
var successCallback = function(data) {
window.cachedTableData = _xmlToTable(data);
retrieveDataCallback(window.cachedTableData);
};
//_basicAjaxRequest1(conData.xmlUrl, successCallback);
//here try another approach not using yql but xmlHttpRequest?
//try xml dom to get url (xml http request)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open('GET', 'https://www.w3schools.com/xml/cd_catalog.xml', true);
xhttp.send();
return;
}
try {
var xmlDoc = $.parseXML(conData.xmlString);
window.cachedTableData = _xmlToTable(xmlDoc);
}
catch (e) {
tableau.abortWithError("unable to parse xml data");
return;
}
}
retrieveDataCallback(window.cachedTableData);
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
window.cachedTableData = _xmlToTable(xmlDoc);
}
// There are a lot of ways to handle URLS. Sometimes we'll need workarounds for CORS. These
// methods chain together a series of attempts to get the data at the given url
function _ajaxRequestHelper(url, successCallback, conUrl, nextFunction,
specialSuccessCallback){
specialSuccessCallback = specialSuccessCallback || successCallback;
var xhr = $.ajax({
url: conUrl,
dataType: 'xml',
success: specialSuccessCallback,
error: function()
{
nextFunction(url, successCallback);
}
});
}
// try the straightforward request
function _basicAjaxRequest1(url, successCallback){
_ajaxRequestHelper(url, successCallback, url, _yqlProxyAjaxRequest2);
}
// try to use yql as a proxy
function _yqlProxyAjaxRequest2(url, successCallback){
var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
var query = "select * from htmlstring where url='" + url + "'";
var restOfQueryString = "&format=xml" ;
var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString + "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
_ajaxRequestHelper(url, successCallback, yqlUrl, _giveUpOnUrl9);
}
function _giveUpOnUrl9(url, successCallback) {
tableau.abortWithError("Could not load url: " + url);
}
// Takes a hierarchical xml document and tries to turn it into a table
// Returns an object with headers and the row level data
function _xmlToTable(xmlDocument) {
var rowData = _flattenData(xmlDocument);
var headers = _extractHeaders(rowData);
return {"headers":headers, "rowData":rowData};
}
// Given an object:
// - finds the longest array in the xml
// - flattens each element in that array so it is a single element with many properties
// If there is no array that is a descendent of the original object, this wraps
function _flattenData(xmlDocument) {
// first find the longest array
var longestArray = _findLongestArray(xmlDocument, xmlDocument);
if (!longestArray || longestArray.length == 0) {
// if no array found, just wrap the entire object blob in an array
longestArray = [objectBlob];
}
toRet = [];
for (var ii = 0; ii < longestArray.childNodes.length; ++ii) {
toRet[ii] = _flattenObject(longestArray.childNodes[ii]);
}
return toRet;
}
// Given an element with hierarchical properties, flattens it so all the properties
// sit on the base element.
function _flattenObject(xmlElt) {
var toRet = {};
if (xmlElt.attributes) {
for (var attributeNum = 0; attributeNum < xmlElt.attributes.length; ++attributeNum) {
var attribute = xmlElt.attributes[attributeNum];
toRet[attribute.nodeName] = attribute.nodeValue;
}
}
var children = xmlElt.childNodes;
if (!children || !children.length) {
if (xmlElt.textContent) {
toRet.text = xmlElt.textContent.trim();
}
} else {
for (var childNum = 0; childNum < children.length; ++childNum) {
var child = xmlElt.childNodes[childNum];
var childName = child.nodeName;
var subObj = _flattenObject(child);
for (var k in subObj) {
if (subObj.hasOwnProperty(k)) {
toRet[childName + '_' + k] = subObj[k];
}
}
}
}
return toRet;
}
// Finds the longest array that is a descendent of the given object
function _findLongestArray(xmlElement, bestSoFar) {
var children = xmlElement.childNodes;
if (children && children.length) {
if (children.length > bestSoFar.childNodes.length) {
bestSoFar = xmlElement;
}
for (var childNum in children) {
var subBest = _findLongestArray(children[childNum], bestSoFar);
if (subBest.childNodes.length > bestSoFar.childNodes.length) {
bestSoFar = subBest;
}
}
}
return bestSoFar;
}
// Given an array of js objects, returns a map from data column name to data type
function _extractHeaders(rowData) {
var toRet = {};
for (var row = 0; row < rowData.length; ++row) {
var rowLine = rowData[row];
for (var key in rowLine) {
if (rowLine.hasOwnProperty(key)) {
if (!(key in toRet)) {
toRet[key] = _determineType(rowLine[key]);
}
}
}
}
return toRet;
}
// Given a primitive, tries to make a guess at the data type of the input
function _determineType(primitive) {
// possible types: 'float', 'date', 'datetime', 'bool', 'string', 'int'
if (parseInt(primitive) == primitive) return 'int';
if (parseFloat(primitive) == primitive) return 'float';
if (isFinite(new Date(primitive).getTime())) return 'datetime';
return 'string';
}
function _submitXMLToTableau(xmlString, xmlUrl) {
var conData = {"xmlString" : xmlString, "xmlUrl": xmlUrl};
tableau.connectionData = JSON.stringify(conData);
tableau.submit();
}
function _buildConnectionUrl(url) {
// var yqlQueryBase = "http://query.yahooapis.com/v1/public/yql?q=";
// var query = "select * from html where url='" + url + "'";
// var restOfQueryString = "&format=xml";
// var yqlUrl = yqlQueryBase + encodeURIComponent(query) + restOfQueryString;
// return yqlUrl;
return url;
}
$(document).ready(function(){
var cancel = function (e) {
e.stopPropagation();
e.preventDefault();
}
$("#inputForm").submit(function(e) { // This event fires when a button is clicked
// Since we use a form for input, make sure to stop the default form behavior
cancel(e);
var xmlString = $('textarea[name=xmlText]')[0].value.trim();
var xmlUrl = $('input[name=xmlUrl]')[0].value.trim();
_submitXMLToTableau(xmlString, xmlUrl);
});
var ddHandler = $("#dragandrophandler");
ddHandler.on('dragenter', function (e)
{
cancel(e);
$(this).css('border', '2px solid #0B85A1');
}).on('dragover', cancel)
.on('drop', function (e)
{
$(this).css('border', '2px dashed #0B85A1');
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) { _submitXMLToTableau(reader.result); };
reader.readAsText(file);
});
$(document).on('dragenter', cancel)
.on('drop', cancel)
.on('dragover', function (e)
{
cancel(e);
ddHandler.css('border', '2px dashed #0B85A1');
});
});
</script>
<style>
#dragandrophandler {
border:1px dashed #999;
width:300px;
color:#333;
text-align:left;vertical-align:middle;
padding:10px 10px 10 10px;
margin:10px;
font-size:150%;
}
</style>
</head>
<body>
<form id="inputForm" action="">
Enter a URL for XML data:
<input type="text" name="xmlUrl" size="50" />
<br>
<div id="dragandrophandler">Or Drag & Drop Files Here</div>
<br>
Or paste XML data below
<br>
<textarea name="xmlText" rows="10" cols="70"/></textarea>
<input type="submit" value="Submit">
</form>
HTML button:
<button type="submit" class="btn btn-default" id="addBtn" onclick="addfunction();">Add</button>
addfunction() code:
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
//upload pic
var filename = selectionfile;
filename = newsID;
var storageRef = firebase.storage().ref(filename);
var uploadTask = storageRef.put(selectionfile);
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
}
}
and this is the validation code
$(function () {
$("#title_span").hide();
var error_title = false;
$("#TitleInput").focusout(function () {
Title_validation();
});
function Title_validation() {
var title = $("#TitleInput").val();
if (title == "") {
$("#title_span").html("wrong input");
$("#title_span").show();
error_title = true;
}
else {
$("#title_span").hide();
}
}
$("#my_form").submit(function () {
error_title = false;
Title_validation();
if (error_title == false) {
return true;
}
else {
return false;
}
});
});
my problem is, when i click the add button, "done" message disappear immediately because the refreshing, i want the message to appear for few second and then refresh the page. how can i do that? knowing that i try to use setTimeout but it does not work.
Change type="submit" to type="button"
If your button has to submit a form remove the type="submit", change the <button> tag to <a> and change your code to the following. You also have to add an ID to your form:
<script>
addfunction() {
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
setTimeout(function () { //wait 5 seconds
document.getElementById(yourForm).submit; //submit your form
}, 5000);
}
}
</script>
OR show the message after everything is send. I think you use a form to submit your data. just add to your <form> action=?done=true
Then you call the script if the variable 'done' is true:
<?php
if (isset($done)) {
echo "<script>your script</script>"; //or do whatever you want if the var is true
}
?>
I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');
I have code to create an indexedDB here:
function create_db() {
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“photos”, 2);
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create photo db
var photo_store = db.createObjectStore("photos", {keyPath: "photo_id"});
var photo_id_index = photo_store.createIndex("by_photo_id", "photo_id", {unique: true});
var dest_id_index = photo_store.createIndex("by_destination_id", "destination_id");
console.log(“store created”);
};
request.onsuccess = function(event) {
console.log(“store opened”);
};
request.onerror = function(event) {
console.log("error: " + event);
};
}
My code to remove entries:
function remove_photos = function (destination_id, db) {
var transaction = db.transaction("photos", "readwrite");
var store = transaction.objectStore("photos");
var index = store.index("by_destination_id");
var request = index.openCursor(IDBKeyRange.only(destination_id));
request.onsuccess = function() {
var cursor = request.result;
if (cursor) {
cursor.delete();
cursor.continue();
}
};
}
How can I delete records using the by_destination_id index so that I can delete all records with a given destination_id, which is an integer?
Thanks for any help.
I found the solution to my issue, the IDBKeyRange.only function doesn't like integers it needs to be a string, so substituting this line in:
var request = index.openCursor(IDBKeyRange.only(destination_id.toString()));
Make the code work.