cannot load image from the local storage using json - javascript

I am a beginner and trying to load local image using json on the browser.
I have 3 questions for this code:
var jsonString = '[{"1":"/models/view/css/pics/dipesh.jpg","2":"/models/view/css/pics/ashish.jpg","3":"/models/view/css/pics/prasun.jpg"}]';
localStorage.setItem("1", jsonString);
var obj = JSON.parse(localStorage.getItem("1"));
$(".player").click(function() {
var img = new Image(150, 150);
for (var i = 0; i < obj.length; i++) {
img.setAttribute("src", obj[i][1]);
document.getElementById(img).style.borderRadius = "8px";
$("#my").html(img);
}
})
<div class="shape" id="my"></div>
my 1st question is:
If I use web path its working. But it shows only 1st image.It is not loading other images.
Therefore I used localStorage to use local image path but its not working.It shows this error:
GET http://localhost:8080/undefined 404 (Not Found)
Question no.3 is, it is not setting the border radius of the image.nad showing this error:
Uncaught TypeError: Cannot read property 'style' of null
Can anybody help me?
Thanx in advance.

Your data is an array with just an object at first index. And it's already JSON :
var jsonString = '[{"1":"/models/view/css/pics/dipesh.jpg","2":"/models/view/css/pics/ashish.jpg","3":"/models/view/css/pics/prasun.jpg"}]';
var jsonObj = JSON.parse(jsonString);
for(var key in jsonObj[0]) {
console.log(jsonObj[0][key])
}

see updated code on fiddle
var jsonString = '[{"1":"https://www.google.co.in/images/srpr/logo11w.png","2":"https://www.google.co.in/images/srpr/logo11w.png","3":"https://www.google.co.in/images/srpr/logo11w.png"}]';
localStorage.setItem("1", jsonString);
var obj = JSON.parse(localStorage.getItem("1"));
$(".player").click(function() {
$.each(obj[0],function(key,value){
var img = new Image(150, 150);
img.setAttribute("src", value);
img.style.borderRadius = "8px";
$("#my").append(img);
});
});

Use $.parseJSON instead as follows,
var jsonString = '[{"1":"/models/view/css/pics/dipesh.jpg","2":"/models/view/css/pics/ashish.jpg","3":"/models/view/css/pics/prasun.jpg"}]';
var obj = $.parseJSON(jsonString);
for(var key in obj[0]) {
console.log(obj[0][key])
}

Related

Cannot download firebase storage files with js loop

I am trying to get the download url of some files of firebase storage with a javascript loop like shown in the code below. It creates the elements correctly but it only assigns a "src" to the second one (in the case of working with 2 files).
var photosContainer = document.getElementById('photosContainer');
var photoNumber = firebase.database().ref('main/' + keyParent).child(key + '/number_photos');
photoNumber.on('value', function(snapshot){
for(var i = 0; i < snapshot.val(); i++){
var divPhoto = document.createElement('div');
photosContainer.appendChild(divPhoto);
var photo = document.createElement('img');
photo.style.width = '100%';
divPhoto.appendChild(photo);
var photosStorage = firebase.storage().ref('main/');
photosStorage.child(i + key).getDownloadURL().then(function(url) {
photo.src = url;
}).catch(function(error) {
// Handle any errors
console.log('An error occurred.')
});
}
})
when getDownloadURL() got its file path from Firebase, the "photo.src = url;" is the second element Object.
it works by creating an array, adding the urls to the array and then erasing the previous elements and creating the new ones inside array.forEach().

Error with iterator in for loop in java script(With onload function in filereader)

The code :
var workbook = XLSX.read(data, {type: 'binary'});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var k=1
var desired_cell = worksheet['A'+k].w;
The above code runs fine
But :
for (var i = 1; i <= 50; i++) {
var obj = {};
var cell = (worksheet[('A'+i)]).w;
obj.PickUpDate = cell;
obj.PickUpTimeSlot = cell;
obj.PickUpAddress = cell;
obj.DeliveryAddress = cell;
obj.BoxType = cell;
array.push(obj);
}
this code gives an error:
Uncaught TypeError: Cannot read property 'w' of undefined
at FileReader.reader.onload
The line:
var cell = (worksheet[('A'+i)]).w;
is fine as I can print the 'cell' to console.
Both the snippet are in FileReader.reader.onload function.
I am using xlsx package https://github.com/SheetJS/js-xlsx
What is wrong with that code?
From the SheetJS/js-xlsx docs :
Built-in export utilities (such as the CSV exporter) will use the w text if it is available. To change a value, be sure to delete cell.w (or set it to undefined) before attempting to export. The utilities will regenerate the w text from the number format (cell.z) and the raw value if possible.
You can't be sure that (worksheet[('A'+i)]).w is defined.
I don't know what your worksheet data is but maybe that could do the job :
var cell = (typeof (worksheet[('A'+i)]).w !== 'undefined') ? worksheet[('A'+i)]).w : worksheet[('A'+i)]).v;
Hope it helps.

Fabric.js lnot loading path object from JSOn

I am using fabric.js to load objects on a canvas. The JSON is returned from a mysql database query.
All object types load fine except for the path object. When the path object attempts to load, I receive an error in firebug.
TypeError: n is not a function
....extend(i,e),i.setSourcePath(s),n(i)}):n(new t.Path(e.path,e))},t.Path.ATTRIBUTE...
Here is my javaScript with two different objects. The rect object loads fine but the path will receive the error.
document.getElementById("save_json").onclick = function(ev) {
var state1 = '{"objects":[{"type":"path","originX":"center","originY":"center","left":344.79,"top":242.77,"width":143.92,"height":16.39,"fill":null,"stroke":"#ffffff","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"round","strokeLineJoin":"round","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","path":[["M",272.8251306873145,250.96509240246408],["Q",272.8251306873145,250.96509240246408,273.3251306873145,250.96509240246408],["Q",273.8251306873145,250.96509240246408,274.0500382534308,250.96509240246408],["Q",274.2749458195471,250.96509240246408,275.69966851789593,250.10266940451746],["Q",277.12439121624476,249.24024640657083,278.5491139145936,248.37782340862424],["Q",279.9738366129424,247.51540041067761,280.923651745175,246.652977412731],["Q",281.87346687740757,245.7905544147844,283.77309714187265,245.3593429158111],["Q",285.6727274063378,244.9281314168378,286.6225425385703,244.06570841889118],["Q",287.5723576708029,243.20328542094455,289.471987935268,242.34086242299793],["Q",291.3716181997331,241.47843942505133,294.2210635964308,240.61601642710474],["Q",297.0705089931285,239.75359342915812,299.44504682370984,239.3223819301848],["Q",301.81958465429125,238.8911704312115,305.6188451832215,238.02874743326487],["Q",309.4181057121517,237.16632443531827,312.2675511088494,236.735112936345],["Q",315.11699650554704,236.30390143737168,320.3409797328261,235.87268993839837],["Q",325.56496296010516,235.44147843942505,329.8391310551517,235.44147843942505],["Q",334.1132991501982,235.44147843942505,340.28709750970984,235.01026694045174],["Q",346.4608958692215,234.57905544147843,351.68487909650054,234.57905544147843],["Q",356.9088623237796,234.57905544147843,362.6077531171749,234.57905544147843],["Q",368.30664391057024,234.57905544147843,372.1059044395005,234.57905544147843],["Q",375.9051649684307,234.57905544147843,380.65424062959346,234.57905544147843],["Q",385.40331629075627,234.57905544147843,387.77785412133767,235.01026694045174],["Q",390.15239195191907,235.44147843942505,393.9516524808493,235.87268993839837],["Q",397.75091300977954,236.30390143737168,400.12545084036094,236.735112936345],["Q",402.49998867094234,237.16632443531827,405.34943406764,237.59753593429159],["Q",408.19887946433767,238.0287474332649,410.0985097288028,238.45995893223818],["Q",411.9981399932679,238.8911704312115,413.42286269161673,238.8911704312115],["Q",414.84758538996556,238.8911704312115,415.79740052219813,238.8911704312115],["Q",416.7472156544307,238.8911704312115,416.7472156544307,239.3223819301848],["L",416.7472156544307,239.75359342915812]],"pathOffset":{"x":344.78617317087264,"y":242.77207392197124}}],"background":""}';
var state2 = '{"objects":[{"type":"rect","originX":"left","originY":"top","left":368.31,"top":284.6,"width":126.33,"height":64.68,"fill":"rgba(0, 0, 0, 0)","stroke":"#ffffff","strokeWidth":3,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","rx":0,"ry":0}],"background":""}';
var jsClean = state1.replace(/"objects"/, 'objects');
var jsonObj = JSON.parse(JSON.stringify(jsClean));
var jsonobj2 = eval('(' + jsonObj + ')');
var obj = new fabric[fabric.util.string.camelize(fabric.util.string.capitalize(jsonobj2.objects[0].type))].fromObject(jsonobj2.objects[0]);
// Add to canvas
canvas.add(obj);
obj.setOpacity(0);
obj.animate('opacity', 100, {
duration: 2000,
onChange: canvas.renderAll.bind(canvas),
});
}
I would really appreciate any and all help from everyone. Thank you so much!!
I was able to fix my own issue. I believe the issue was with the json data and parsing. I also used the enlivenObjects method.
document.getElementById("save_json").onclick = function(ev) {
var state1 = '{"objects":[{"type":"path","originX":"center","originY":"center","left":344.79,"top":242.77,"width":143.92,"height":16.39,"fill":null,"stroke":"#ffffff","strokeWidth":5,"strokeDashArray":null,"strokeLineCap":"round","strokeLineJoin":"round","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","path":[["M",272.8251306873145,250.96509240246408],["Q",272.8251306873145,250.96509240246408,273.3251306873145,250.96509240246408],["Q",273.8251306873145,250.96509240246408,274.0500382534308,250.96509240246408],["Q",274.2749458195471,250.96509240246408,275.69966851789593,250.10266940451746],["Q",277.12439121624476,249.24024640657083,278.5491139145936,248.37782340862424],["Q",279.9738366129424,247.51540041067761,280.923651745175,246.652977412731],["Q",281.87346687740757,245.7905544147844,283.77309714187265,245.3593429158111],["Q",285.6727274063378,244.9281314168378,286.6225425385703,244.06570841889118],["Q",287.5723576708029,243.20328542094455,289.471987935268,242.34086242299793],["Q",291.3716181997331,241.47843942505133,294.2210635964308,240.61601642710474],["Q",297.0705089931285,239.75359342915812,299.44504682370984,239.3223819301848],["Q",301.81958465429125,238.8911704312115,305.6188451832215,238.02874743326487],["Q",309.4181057121517,237.16632443531827,312.2675511088494,236.735112936345],["Q",315.11699650554704,236.30390143737168,320.3409797328261,235.87268993839837],["Q",325.56496296010516,235.44147843942505,329.8391310551517,235.44147843942505],["Q",334.1132991501982,235.44147843942505,340.28709750970984,235.01026694045174],["Q",346.4608958692215,234.57905544147843,351.68487909650054,234.57905544147843],["Q",356.9088623237796,234.57905544147843,362.6077531171749,234.57905544147843],["Q",368.30664391057024,234.57905544147843,372.1059044395005,234.57905544147843],["Q",375.9051649684307,234.57905544147843,380.65424062959346,234.57905544147843],["Q",385.40331629075627,234.57905544147843,387.77785412133767,235.01026694045174],["Q",390.15239195191907,235.44147843942505,393.9516524808493,235.87268993839837],["Q",397.75091300977954,236.30390143737168,400.12545084036094,236.735112936345],["Q",402.49998867094234,237.16632443531827,405.34943406764,237.59753593429159],["Q",408.19887946433767,238.0287474332649,410.0985097288028,238.45995893223818],["Q",411.9981399932679,238.8911704312115,413.42286269161673,238.8911704312115],["Q",414.84758538996556,238.8911704312115,415.79740052219813,238.8911704312115],["Q",416.7472156544307,238.8911704312115,416.7472156544307,239.3223819301848],["L",416.7472156544307,239.75359342915812]],"pathOffset":{"x":344.78617317087264,"y":242.77207392197124}}],"background":""}';
var stateFin = JSON.parse(state1);
fabric.util.enlivenObjects([stateFin.objects[0]], function(objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
objects.forEach(function(o) {
canvas.add(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});
}

threeJS jsonLoader - "Cannot read property 'length' of undefined"

I'm creating a scene, which can be saved and then loaded.
To save the scene,I serialize all the objects (and their data). For the meshes this works simply like this:
var json = {};
json.objectsInScene = [];
for (var i = 0; i < collectionOfObjects.length; i++)
{
json.objectsInScene.push(collectionOfObjects[i].toJSON();
}
Then, I try to load them back in which works like this:
var jsonObject = JSON.parse(json);
for (var i = 0; i < jsonObject.objectsInScene.length;i++){
var loader = new THREE.JSONLoader();
var geometry = loader.parse(jsonObject.objectsInScene[i]);
var mesh = new THREE.Mesh(geometry.geometry, new THREE.MeshBasicMaterial());
this.scene.add(mesh);
}
When I execute this code. I get the following error:
Cannot read property 'length' of undefined
Line 14990 of three.js.
Which is this line:
zLength = vertices.length;
And when checking it in the dev tools, I have to agree: vertices.length is undefined. In fact, it gets assigned a couple of lines above that:
var vertices = json.vertices;
But the json-object only contains the following properties:
geometries: Array[15]
materials: Array[15]
metadata: Object
object: Object
What am I doing wrong? Where does it go wrong, or what can I do to work around this issue?
R73
maybe you should use THREE.ObjectLoader
for (var i = 0; i < jsonObject.objectsInScene.length;i++){
var loader = new THREE.ObjectLoader();
var obj= loader.parse(jsonObject.objectsInScene[i]);
this.scene.add(obj);
}

Get String Value of Blob Passed to e.parameter in Apps Script

I'm using this code to get a blob passed to a function:
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
This is the error I get:
Execution failed: TypeError: Can not find getDataAsString function in
the Blob object.'arrayBlob'
How do I get the string value of this blob?
Here is my code:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = userProperties.getProperty('savedArray');
arrayList = JSON.stringify(arrayList);
var arrayBlob = Utilities.newBlob(arrayList);
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
arrayList = JSON.parse(arrayList);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
I'd like the solution worked with more than one user simultaneous using the script.
Update:
Add a global variable OUTSIDE of any function:
var arrayBlob = Utilities.newBlob("dummy data");
function showList(folderID) {
Code here ....
};
Check that the code has access to the blob:
function submit(e){
Logger.log("arrayBlob.getDataAsString(): " + arrayBlob.getDataAsString());
//More Code . . .
}
This solution eliminates the need of embedding a hidden element in the dialog box with a value of the blob.
You won't need this line:
panel.add(app.createHidden('arrayBlob', arrayBlob));
There are other changes I'd make to the code, but I simply want to show the main issue.
Old Info:
In the function showList(), the method getDataAsString() works on the blob named arrayBlob.
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
In the function, submit(), the same method does not work.
var arrayBlob = e.parameter.arrayBlob;
In the function showList(), the code is assigning a newBlob to the variable arrayBlob. So arrayBlob is available to have the getDataAsString() method used on it.
var arrayBlob = Utilities.newBlob(arrayList);
In the function, submit(), you are trying to pass the arrayBlob blob variable into the submit() function, and reference it with e.parameter.
If you put a Logger.log() statement in the submit() function.
function submit(e){
Logger.log('e: ' + e);
Logger.log('e.parameter` + e.parameter);
var arrayBlob = e.parameter.arrayBlob;
Those Logger.log statements should show something in them. If there is nothing in e.parameter, then there is nothing for the .getDataAsString() to work on.
It looks like you are putting the arrayBlob into a hidden panel.
panel.add(app.createHidden('arrayBlob', arrayBlob));
But when the object is getting passed to the submit(e) function, the arrayBlob might not be getting put into that object.
So, what I'm saying is, the:
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
Line may be perfectly good, but there is no arrayBlob there to work on. This hasn't fixed your problem, but do you think I'm understanding part of what is going on?
I'm not sure why you are using Blob's here at all, you could simply work with JSON instead.
However, if you have a reason to use Blobs, you can pass the JSON data through your form and create the Blob in your handler, as the modified code below does:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = UserProperties.getProperty('savedArray');
//get JSON data pass through form.
var arrayBlob = JSON.stringify(arrayList);
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
//include JSON Data in the form.
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = Utilities.newBlob(e.parameter.arrayBlob);
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
In the method you were using originally, the Blob itself was never included in the form, you were simply passing the string "Blob" around.
This is because the function createHidden(name, value); expects two strings as parameters, so it calls ".toString()" on the arrayBlob object, which returns the string "Blob".

Categories

Resources