How can I display the snapshot data in HTML? - javascript

I'm trying to display the snapshot data from the database to the html page, but it seems to display an '[object Object]'instead of the gmail.
I'm new to code so please be patient.
here is the code:
firebase.database().ref('gmails/').get().then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
var content = '';
// give each message a unique ID
content += "<li>";
content += snapshot.val();
content += "</li>";
document.getElementById("gmails").innerHTML += content;
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
THE HTML:
<ul id="gmails">
</ul>
enter image description here
In the image you can see the object instead of the value

It sounds like you have a javascript Object which contains data that you want to render as text on your page. When you see [object Object] it's a sign that you're trying to render something as text that your code doesn't know how to turn into text, in this case your snapshot object.
There are a few simple things you can try / questions you can answer for yourself:
What is the "shape" of your snapshot object? Do you know the names of variables it contains? Are they supposed to be strings? Is it wrapping HTML of some kind? If so, you'll probably want to render either specific strings inside the object or one big string contained inside. If it's HTML I believe you can just insert it the way you already are.
If you don't know the structure of the contents of snapshot, there are some easy ways to figure it out:
If you know how to use the Chrome debugger ("source" tab of the dev tools, ctrl-P or command-P to search for your relevant file, and click on the line number to add a breakpoint), put a breakpoint on console.log(snapshot.val()); and inspect the value of snapshot. You can hover over it and click into its child-objects, and determine their names and structure for accessing and finding the strings you want to display
If you want a simple solution without tools, you can change console.log(snapshot.val());
...to:
console.log(JSON.stringify(snapshot));
...and see how your data is structured as JSON. That will just drop the whole object into your console, which I assume is just displaying `[object Object] as-is.
Once you have that figured out, you should be able to access the right children of snapshot that contain the text you're trying to render.

Related

How can I modify the name of an html file when clicking on a link?

I'm currently using an API which returns a lot of data and I want to be able to send the user to another page when they click on a name. Here's my Javascript:
const name = pokemon.name;
${name}
Where ${name} varies according to the name of the Pokemon.
The problem is that I want to create one HTML file with the same structure with the same Pokemon but different info. I know that it's possible because I have seen other sites with "/pokemonName" at the end of the URL in the address bar.
Edit : I'm using vanilla JS and the API is PokeApi
So you want something like this: https://dev.to/js_bits_bill/vanilla-js-who-s-that-pokemon-game-with-pokeapi-34m4
I see your example is exactly the same as the tutorial, the only issue is that you will notice that in the tutorial he is wrapping the html around backticks "`".
This is because those "${}" only works if wrapped in backticks.
You would need something like:
function pageHtmlString (name) {
return `<button data-name="${name}">${name}</button>`;
};

Local Storage display problems

i'm trying to use localstorage to append recent city searches from user to a form element.
The problem is now im very unsure of how to progress further if .innerHTML wipes out all text
when it's putting anything into the element. the end goal would be for the form element to look something like
athens
paris
chicago
any ideas on how to implement this?
new to local storage so would appreciate any help
here's an example of the code :)
// HTML
<form class="recent-search" id="demo"></form>
// JAVASCRIPT
function setStorage() {
// here i'm trying to store nameValue to localstorage
localStorage.setItem('', nameValue);
}
setStorage()
function getValue() {
// now i'm getting nameofcity from localstorage
return localStorage.getItem('nameofcity');
}
// console logging it so i can make sure it's working (it is)
console.log(getValue());
function myFunction() {
// now i set the innerHTML of the element with the ID of "demo" to be "1. "nameofcity"
document.getElementById("demo").innerHTML = '1. ' + localStorage.getItem('nameofcity');
}
myFunction();
if you'd like more context heres the github repository https://github.com/LukeMcHenry311/Server-Side-Weather
You're saving the value to the key of an empty string and then trying to retrieve the key of nameofcity, which you probably didn't save it to. localStorage works by key-value pairs. You can always go to your browser's dev tools (usually by hitting F12), and under Application tab you can see what's in your local storage
It should be something like
function setStorage() {
localStorage.setItem('nameofcity', nameValue);
}

image url showing as undefined discord.js

so I'm making a discord bot as a small project and when I try to get the url from an image attachment it shows up as undefined.
here's my code:
var attachment = message.attachments
if (message.content.includes("is dropping 3 cards!")) {
let image = attachment
console.log(image.url)
}
when I use this code the image url shows up as undefined and I don't know why. I've tried using image without .url and the url seems to show up but when I use .url it doesn't seem to work.
Now now, message.attachments contains an array. The attachment can be image, video or file. There can be also multiple attachments in one message. Meaning that you need to define which one of the attachments you want to use. You should also check if there is any attachments in the message before going forward.
Below is little example for using the first file/image in the message:
if(message.attachments.size > 0) {
var attachment = message.attachments.first();
console.log(attachment.url)
}
Try console logging just attachment and seeing if that gives you any results. It should return an array of attachments which you would either need to map through or set an index value to your attachment ie. attachment[0].url. Also, there's no need for declare the image variable as its not saving you any time. attachment.url is the same thing as image.url and it just makes things more confusing than it needs to be.

How to insert an image into Word from a URL

I am currently working on an Office.js add in for Word and I am trying to insert an image from a given Url. I was reviewing the Office.js documentation which is located at :
InlinePicture class (JavaScript API for Word)
I see that they may have a built in functionality of getting the base64 representation from a img url by "getBase64ImageSrc()". The documentation on the dev office website is either misleading or incorrect.
Looking to see if anyone has built a word-addin that inserts an image from a url using "getBase64ImageSrc()"? Or am I looking in the wrong direction.
Need to elaborate more on Mike's answer, to avoid confusion.
Staffer901: you are talking about 2 different subjects on this post.
Inserting Images to the document. which i think is your bottom line question: how to insert an image with an image URL. The options that Michael mentioned, which are basically to insert classic HTML for an image, will work but i would NOT recommend you to use any of them. The reason why is because really what you are doing is storing a reference to the image that has a connection to the internet dependency, which means any user consuming that document must be connected to see the image.
What i DO recommend you to do for image insertion (permanent insertion :) ) is to use the range.insertInlinePictureFromBase64 method. You need to have an additional step to encode the image in the URL to a base64 string, which is what the methods accepts as input parameter and here is a good discussion on how to achieve this.. Check out a sample below showing inserting an InlinePicture on the first paragraph of the document, assumes you have the base64. Note that you can get the current insertion point and insert the pic there if needed as well. insertInlinePictureFromBase64 is a method of any objects that inherits from range, like body, paragraph, content control etc.
here is a sample:
// Run a batch operation against the Word object model.
Word.run(function (context) {
// Create a proxy object for the paragraphs collection.
var paragraphs = context.document.body.paragraphs;
// Queue a commmand to load the style property for all of the paragraphs.
context.load(paragraphs);
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
// Queue a command to get the first paragraph.
var paragraph = paragraphs.items[0];
var b64encodedImg = "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";
// Queue a command to insert a base64 encoded image at the beginning of the first paragraph.
paragraph.insertInlinePictureFromBase64(b64encodedImg, Word.InsertLocation.start);
// Synchronize the document state by executing the queued commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Added an image to the first paragraph.');
});
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
Finally note that the setSelectedDataAsync method that Michaels mentioned, was recently updated to support image insertion, you also need to supply the base64 of the image but the benefit is that you get backwards compatibility (it will work with 2013 clients as well) here is a code sample of this:
// assumes a valid base64 is provided as the first parameter.
Office.context.document.setSelectedDataAsync(mybase64, { coercionType: 'image' }, function (result) {
if (result.status == 'succeeded')
app.showNotification("Image inserted");
else
app.showNotification("Error:" + result.error.message + " : " + error.name)
})
Consuming images from the document. This is about getting the base64 from existing images in the document. We have a body. inlinePictures collection you can use to get all the images in the document, and you use the getBase64 method to get the base64 encoded representation of the binary. I would like to know why this is confusing in the documentation, can you please elaborate on that?
I hope this is useful.
thanks and happy coding!
-Juan.
To insert an image from URL in Word, use either the Range.insertHtml method or the Document.setSelectedDataAsync method, depending on your specific scenario and goals.
It looks like there's an error in the documentation for the other method you linked to - I'll make sure that gets corrected, but I don't believe it's the API you're looking for.

How to save multiple objects to an array in a chrome extension?

I'm building my first chrome extension and I want it to track the TV series I watch and I'm currently trying to get it to save metadata on the series that I am following.
I have a content script that returns the title, the newest episode (and the URL of this episode) as well as the URL of the cover image of the series. I am currently trying to save it with some code on my background script (I have made sure to include "storage" under the permissions section of the manifest file).
So far my script looks like this (This was developed with help from Trying to save and fetch a Javascript object using chrome.storage API?):
var bkg = chrome.extension.getBackgroundPage();
response.aID = new Series(response.aTitle,response.aNewEp,response.aNewEpURL,response.aImage);
chrome.storage.sync.set(response.aID, function(){
chrome.storage.sync.get(function(val){
bkg.console.log("The saved title is: ", val.anTitle);
bkg.console.log("The saved newEp is: ", val.anNewEp);
bkg.console.log("The saved newEpURL is: ", val.anNewEpURL);
bkg.console.log("The saved imageURL is: ", val.anImage);
});
});
Problem is, the script only seems to store one response.aID at a time, so I can never store data for more than 1 TV series. Every time I try, the script seems to overwrite my previous entry. So I would like to ask whether there's any way to store more than 1 TV series at a time?
I have looked at storing an array and then pushing each new object into that array (Store an array with chrome.storage.local), but I don't quite understand the syntax involved so I'm not sure if this would work for me.
Unfortunately you didn't include the piece of code where you save your data, but i think you dont store your data with indices for the different TV series so the stored one gets overwritten everytime you store another one.
Anyway I would prefer storing your data in a JSON element (basically every javascript element can by converted to one but continue reading) because js provides several functions for this format which make it quite easy to use.
When opening your extension, load the data and call
var data = JSON.parse (yourloadedstring);
so the string (which should look like {"TVShows": [{"title": "How i met your mother", "url": ...}, {...}]} (look here for an explenation how JSON works) gets "translated" to an element from which you can read simply by calling
data.TVShows[0].title
or
data.TVShows[1].imageURL
You can edit this data JSON element when you add a new show for example by saying
data.TVShows[2].title = "The Big Bang Theory";
data.TVShows[2].URL= ...;
data.TVShows[2].imageURL= ...;
and save this element to chromes storage by calling
var dataToSave = JSON.stringify(data);
You have a string in your storage then, containing all information you need and you can simply parse it later like explained above :)
I hope everything is clearly to understand, if not pls ask me!
Cheers

Categories

Resources