Can't get data out of indexedDB - javascript

Here's the function I'm trying to call:
function restoreCurrent() {
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2);
tzact.onerror = function(event) {
alert ("Failed to retrieve the data.");
}
tzact.onsuccess = function(event) {
document.getElementById("demo").innerHTML += "Transaction success.<br />";
}
}
window.onload = function() {
restoreCurrent();
}
As you can see, it should output something on either a success or an error. In fact it doesn't output anything. I had further code after this in the .onsuccess function, but nothing gets executed. And the line where it stops working is the database call, I've tested that much.
For the record, both this line of code when I created the database
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").add({id : 2, pictureData : working});
and this line when I try and update that particular record
var tzact = db.transaction(['Picture'], "readwrite").objectStore("Picture").put({id : 2, pictureData : working});
seemed to execute OK -- or at least, the functions they were embedded in went on to output success messages. Without being able to extract any data it's hard to be sure.
EDIT: Figured it out myself. The answer is that I had to put this into each function:
var request = window.indexedDB.open("[database name]",5);
request.onerror = function() {
alert ("Failed to open the database.");
}
request.onsuccess = function() {
var db = request.result;
var tzact = db.transaction(['Picture'],"readonly").objectStore("Picture").get(2); // or "readwrite" and .put(2), as the case might be
tzact.onerror=function() {
alert ("Data transaction failed.");
}
tzact.onsuccess=function() {
document.getElementById("demo").innerHTML += "Data transaction successful.<br />";
if (tzact.result) {
var working = tzact.result.pictureData;
// the rest of the function goes here
} else {
alert ("No data received.");
}
}
}

Related

uilocations is declared but its value is never read

I'm building a price prediction model using Python, Flask Server, HTML, and CSS. I've implemented the HTML and CSS code but I'm having issues getting my dropdown button to read all my locations via a JavaScript call (all the locations are saved in a json file). Concerning 'uilocations' it keeps showing 'uilocations is declared but its value is never read. Below is my javascript code:
function onClickedEstimatedPrice(){
var uiBathrooms = document.getElementsByName("uiBathrooms");
for(var i in uiBathrooms) {
if(uiBathrooms[i].checked) {
return parseInt(i)+1;
}
}
return -1;
}
function getBHKValue() {
var uiBHK = document.getElementsByName("uiBHK");
for(var i in uiBHK) {
if(uiBHK[i].checked) {
return parseInt(i)+1;
}
}
return -1; // The above functions iterate through the buttons and return the values
}
function onClickedEstimatedPrice() {
console.log("Estimated price button clicked");
var sqft = document.getElementById("uilocations");
var bathrooms = document.getElemenbtById("uiEstimatedPrice");
var estPrice = document.getElementById("uiEstimatedPrice")
var url = "http://127.0.0.1:5000/predict_home_price"; //url for the price prediction endpoint
$.post(url, { //This is a jquery POST call that makes a POST call to the url, we will get our output back in 'data'
total_sqft: parseFloat(sqft.value),
bhk: bhk,
bath: bathrooms,
location: location.value
},function(data, status) {
console.log(data.estimated_price);
estPrice.innerHTML = "<h2>" + data.estimated_price.toString() + " Lakh</h2>";
console.log(status)
}
)
}
function onPageLoad() {
console.log( "document loaded" );
var url = "http://127.0.0.1:5000/get_location_names"; //Here we make our HTTP Call
$.get(url,function(data, status) { //This is a jquery GET call that makes a GET call to the url, we will get our response back in the 'data'
console.log("got response for get_location_names request");
if(data) {
var locations = data.locations; //This will be our list of locations
var uilocations = document.getElementById("uilocations");
$("#uilocations").empty();
for(var i in locations) {
var opt = new Option(locations[i]);
$("#uilocations").append(opt);
} //The above goes through our locations one by one and adds them to our dropdown
}
});
}
window.onload = onPageLoad; //This will be used to load our HTML page and load the locations
I tried the code above, i expected my dropdown button to pick more locations but whenever i refresh the page on my browser, i don't get the expected output

How to preload JSON link?

I've got a function that needs to call a link (JSON format), the fact is that I would like to be able to preload this link to smooth and reduce the operation time when calling the function.
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
colorMe(data.target)
}
});
}
function colorMe(item){
globalItem = item;
request('http://blablabla/?format=json',findMaterial);
};
function findMaterial(data){
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
function findMatchArea(areas){
jq310.each(areas, function(area) {
blablabla
The request function that I built just look if the link as been already called, so it's reloading it if true. And also send data from the link to the called function.
If you'r looking to load a static json file you should concider loading it on the top of your file. To do so you should store the datas in a global variable like that :
let datas;
request('http://blablabla/?format=json', (data) => {
datas = data
});
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
globalItem = data.target;
findMaterial();
}
});
}
function colorMe(item){
globalItem = item;
};
function findMaterial(){
const data = datas;
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
I finally found a way to do it properly, here it is :
var mylink = 'https://fr.wikipedia.org/wiki/JavaScript';
function preloadURL(link){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", link, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
return jsonObject;
};
jsonObjectInv = preloadURL(mylink);
And I just point to my json variable to parse it (really faster)
function colorMe(item){
globalItem = item;
findMaterial(jsonObjectInv);
};
Problem solved

API Jive get categories error : Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/

i use Jive and i want to get all categories and for each category, i want to create a checkbox for each of them.
Currently, i have my array with all categories, but when i try to create checkbox, it return me this error :
" Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/ "
Someone can help me ?
///////////////// function checkbox for each category ////////////////
$("#submit_a_question").click(function(e) {
e.preventDefault();
$("#modal").addClass('is-show');
$("#ideasContainer").height((height + 100) + "px");
resizeIframe();
fieldsPlaceholder(appLang);
var categoriesToShow = categories(placeID);
var container = $('#listCheckboxCategories');
var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = $('input />', {type: 'checkbox'});
if(tileConfig.isThereFilterRadios == "Yes"){
$('#ShowCategories').show();
$('#listDropdownCategories').show();
$.each(categoriesToShow.res, function(index, value) {
CheckboxCreate.appendTo(container);
});
}
///////// function to get all categories in an array /////////
function categories(placeID){
var request = osapi.jive.corev3.places.get({
uri : '/api/core/v3/places/' + placeID
});
// var res = [];
request.execute(function(response) {
if (typeof response.error != 'undefined') {
console.log("API call failed");
} else {
console.log(response);
response.getCategories().execute(
function (res){
console.log("cat",res);
});
}
});
}
I was able to execute the call successfully by using "/places/{placeId}" in the URI as below:
osapi.jive.corev3.places.get({uri: '/places/1003'}).execute(function(response) {
console.log(response);
});
For which I have received the place object in the response, as expected:
{ type: "space",
parent: "http://localhost:8080/api/core/v3/places/1000",
placeTopics: Array(0),
displayName: "water-cooler",
iconCss: "jive-icon-space", …}
Are you sure your "placeId" has the correct value? Maybe log the URI you are sending before making the call and check if the format matches the one I have mentioned above. Thanks.

XMLHttpRequest Error Checking- Better way to write this?

I wrote a webpage that runs from the desktop to grab information off of a public website. I am trying to make it to where 1) if there is no internet connection there is a alert 2) if there is a an internet connection but somehow the info was not retrieved correctly, the user would be alerted.
The try and catch works for the test if there is no internet connection.
I am using the xml.status codes for the second test...if the website is active but the info that is pulled is messed up....that test condition isn't working the way I wanted it. I tried giving the xml.open a bogus website and was expecting a non 200-300 status code. But it did not work...instead the catch statement was activated. Why is this? And is there a better way to write this?
Also, on a side note I had return ""; because I the calling variables that use this could not be have null or undefined: variable = getInfo(); n.setAttribute("placeholder", variable);
function getInfo() {
var xml = null;
xml = new XMLHttpRequest();
try {
xml.open("get", "http://example.asp", false);
xml.send(null);
if ((xml.status >= 200 && xml.status <= 300) || xml.status == 304) {
var hi = xml.responseText;
hi = hi.replace(/(\r\n|\n|\r)/gm, "");
var what1 = /winning_number_sm.*?ul/
var what2 = /\d+/g
hi = what1.exec(hi);
var temp;
for (i = 0; i < 6; i++) {
if (null !== (temp = what2.exec(hi))) {
numbers[i] = temp;
}
}
return numbers;
} else {
alert("Error Connecting to Website! You will have to eneter informatin by hand");
return "";
}
} catch (e) {
alert("No Internet Connection! You will have to enter information by hand");
return "";
}
}
I don't know if you can use jQuery framework but to get error from an ajax connection (test if a website is up) you can do easely that :
//your ajax object
var request = $.ajax({
url: "http://www.exemple.com/script.php",
type: "POST",
data: {/*your datas*/},
dataType: "html"
});
request.done(function(msg) {
//make your stuff automatically
});
request.fail(function(jqXHR, textStatus) {
alert( "Error Connecting to Website! You will have to enter informatin by hand");
});
An other approch can be to call a local php script whose test distant url with curl function (ex : http://www.php.net/manual/en/function.curl-error.php)

Uncaught TypeError: Object has no method ... Javascript

I'm having an issue where I get an error that says...
"Uncaught TypeError: Object f771b328ab06 has no method 'addLocation'"
I'm really not sure what's causing this. The 'f771b328ab06' is a user ID in the error. I can add a new user and prevent users from being duplicated, but when I try to add their location to the list, I get this error.
Does anybody see what's going wrong? The error occurs in the else statement of the initialize function as well (if the user ID exists, just append the location and do not create a new user). I have some notes in the code, and I'm pretty sure that this is partly due to how I have modified an example provided by another user.
function User(id) {
this.id = id;
this.locations = [];
this.getId = function() {
return this.id;
};
this.addLocation = function(latitude, longitude) {
this.locations[this.locations.length] = new google.maps.LatLng(latitude, longitude);
alert("User ID:" );
};
this.lastLocation = function() {
return this.locations[this.locations.length - 1];
};
this.removeLastLocation = function() {
return this.locations.pop();
};
}
function Users() {
this.users = {};
//this.generateId = function() { //I have omitted this section since I send
//return Math.random(); //an ID from the Android app. This is part of
//}; //the problem.
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
this.getUser = function(id) {
return this.users[id];
};
this.removeUser = function(id) {
var user = this.getUser(id);
delete this.users[id];
return user;
};
}
var users = new Users();
function initialize() {
alert("Start");
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data){
var user_id = data[0];
var latitude = data[1];
var longitude = data[2];
if (typeof users.users[user_id] === 'undefined') {
users.createUser(user_id);
users.users[user_id] = "1";
user_id.addLocation(latitude, longitude); // this is where the error occurs
}
else {
user_id.addLocation(latitude, longitude); //here too
alert(latitude);
}
}
})
}
setInterval(initialize, 1000);
Since I get the ID from the phone and do not need to generate it here (only receive it), I commented out the part that creates the random ID. In doing this, I had to add a parameter to the createUser method within Users() so that I can pass the ID as an argument from Initialize(). See the changes to createUser below:
Before, with the generated ID (the part where the number is generated is in the above code block with comments):
this.createUser = function() {
var id = this.generateId();
this.users[id] = new User(id);
return this.users[id];
};
After, with the ID passed as an argument:
this.createUser = function(id) {
this.users[id] = new User(id);
return this.users[id];
};
If anyone has any suggestions I would really appreciate it. Thanks!
Here you're getting user_id by :
var user_id = data[0];
So it's a part of the json answer : maybe a string or another dictionnary, this can't be a user object. You should try to update your code in your success function inside the "if" block by :
user = users.createUser(user_id);
//The following line is a non sense for me you put an int inside
//an internal structure of your class that should contain object
//users.users[user_id] = "1";
user.addLocation(latitude, longitude);

Categories

Resources