how to display name from firebase - javascript

I have this part of my code and I am trying to have the user name display from firebase when a user comes to map. but when I run the code it erase all the html and prints 2 lines of code :
5Frederick619
•5Profile-10
essentially erasing all my code
<!--you can-->
<div class="row">
<div class="col-md-12 youcan">
<h4>You can:</h4>
<ul>
<li><span>1</span> Track the location your friends my brother</li>
<li><span>2</span> Track the location your friends my brother</li>
<li><span>3</span> Track the location your friends my brother</li>
<li><span>4</span> Track the location your friends my brother</li>
<script>
var endpoint;
endpoint = new Firebase('https://keepitstreet.firebaseio.com/maps/openmap');
endpoint.on('child_added', function(childSnapshot) {
var uuid = childSnapshot.key()
var point = childSnapshot.val()
var username = childSnapshot.val();
var name = username.name;
document.write('<li><span>5</span>'+ name +'</li>');
})
</script>
</ul>
</div>
</div>
<!--/you can-->

document.write is meant to be used when opening a new window and inserting content into it, so when called on a loaded document, it will clear it. that's why your entire html is being deleted, except for the last thing your writing to the document.
what you need is to add the new item. you could do something like this:
function getPosts() {
var endpoint;
var list = document.querySelector('.youcan ul');
endpoint = new Firebase('https://keepitstreet.firebaseio.com/maps/openmap');
endpoint.on('child_added', function(childSnapshot) {
var uuid = childSnapshot.key()
var point = childSnapshot.val()
var username = childSnapshot.val();
var name = username.name;
appendPosts(name)
})
function appendPosts(name) {
var li = document.createElement('li');
li.textContent = name;
list.appendChild(li);
}
}

Related

Preview Email Template based on drop down, Send email once your satisfuied

in my Google Sheets app script, I currently have three template.html files and a few scripts; I'd like to create a preview email and send it to the user once he or she is satisfied; however, the event listeners that (openAI) built for me do not work; when I change the Drop Down Menu or click send Button, nothing happens and the preview does not load. When I ask the AI for help, it keeps modifying my code; My code no longer looks like the original; after a week of trying, I've realized that I need assistance with this. Here's my most recent code as of today. The AI also insisted on using Google Drive, which I declined because I have the HTML files in the app scrip sheet itself and used to obtain it with this.
This code is not used anymore, But use to work when I used it in GmailApp to get the template File Name.
var html = HtmlService.createTemplateFromFile('Proposal Template.html');
var html = HtmlService.createTemplateFromFile('Marketing Template.html');
var html = HtmlService.createTemplateFromFile('Trusted Partner Template.html');
Keep in mind that while I am not an expert in Jave or JS, I am familiar with them.
My code
function showEmailPreview() {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var title = sheet.getRange(row, getColIndexByName("Title")).getValue();
var company_location = sheet.getRange(row, getColIndexByName("Company Location")).getValue();
var company_phone1 = sheet.getRange(row, getColIndexByName("Company Phone 1")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName;
// Create the select element
const select = `
<select id="template-select">
<option value="Proposal Template.html">Proposal Template</option>
<option value="Marketing Template.html">Marketing Template</option>
<option value="Trusted Partner Template.html">Trusted Partner Template</option>
</select>
`;
// Create the button element
const button = `<button id="send-button">Send Email</button>
<div id="preview"></div>`; //This could be a issue? The ai did not know where to place this or cut down before giving me a proper answer.
// Create an HTML output page that displays the email template, the select element, and a button to send the email
var output = HtmlService.createHtmlOutput(`
<script>
var buttonElement;
function getElementById(id) {
return document.getElementById(id);
}
function init() {
// Add a change event listener to the select element
document.getElementById('template-select').addEventListener('change', function() {
// Get the selected template file name
var templateFile = this.value;
// Read the contents of the selected file
var template = readFile(templateFile);
// Set values in the template
var html = HtmlService.createTemplate(template);
html.userFullName = userFullName;
html.userCompanyName = userCompanyName;
html.title = title;
html.company_location = company_location;
html.company_phone1 = company_phone1;
// Get the filled-in email template as a string
var emailTemplate = html.evaluate().getContent();
// Update the preview window with the selected template
document.getElementById('preview').innerHTML = emailTemplate;
});
// Add a click event listener to the button element
buttonElement = getElementById('send-button');
buttonElement.addEventListener('click', function() {
// Get the selected template file name
var templateFile = document.getElementById('template-select').value;
// Pass the selected template file name as an argument to the sendEmail function
sendEmail(templateFile);
});
}
window.onload = init;
function sendEmail(templateFile) {
// Read the contents of the selected file
var template = readFile(templateFile);
// Set values in the template
var html = HtmlService.createTemplate(template);
html.userFullName = userFullName;
html.userCompanyName = userCompanyName;
html.title = title;
html.company_location = company_location;
html.company_phone1 = company_phone1;
// Get the filled-in email template as a string
var emailTemplate = html.evaluate().getContent();
// Send the email
GmailApp.sendEmail(userEmail, subjectLine, '', {htmlBody: emailTemplate});
}
</script>
<script>
init();
</script>
${select}
${button}
`)
.setWidth(950)
.setHeight(750)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
// Display the output page in a modal dialog box
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
//output.evaluate();
//window.onload = init;
};
function readFile(templateFile) {
// Get the contents of the selected file
var file = DriveApp.getFilesByName(templateFile);
var contents = file.next().getBlob().getDataAsString();
return contents;
}//window.onload = init;
Results.
Here is a link for testing.
https://docs.google.com/spreadsheets/d/1gXDbtjCYfZw8kOaOMorbJ54dXyl7bh6MFM1LopTrNww/edit?usp=sharing
Its always like this when you struggle for a week and give up, And you finally post something and then you find yourself a solution. So here is the correct way of doing it.
Let's first talk about the menu. I created a file template-select-menu.gs
<form>
<label for="template">Select a template:</label><br>
<select id="template" name="template">
<option value="Proposal Template.html">Proposal Template</option>
<option value="Markting Template">Marketing Template</option>
</select>
<br><br>
<input type="button" value="Preview" onclick="google.script.run.onTemplateSelected(document.forms[0].template.value)">
</form>
then I have my preview_email.gs
function showEmailPreview() {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var rate = sheet.getLastRow();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName ;
var aliases = GmailApp.getAliases()
// Create the email template selection menu
var proposalTemplate = HtmlService.createTemplateFromFile('Proposal Template.html');
var marktingTemplate = HtmlService.createTemplateFromFile('Markting Template.html');
var selectMenu = HtmlService.createTemplateFromFile('template-select-menu.html');
var selectMenuHtml = selectMenu.evaluate().getContent();
// Create an HTML output page that displays the email template selection menu and a button to send the email
var output = HtmlService.createHtmlOutput(selectMenuHtml)
.setWidth(600)
.setHeight(450);
// Display the output page in a modal dialog box
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
}
/**
* This function is called when the user selects a template from the drop-down menu.
* It creates an email preview using the selected template and displays it in the modal dialog box.
*/
//var html = HtmlService.createTemplateFromFile(templateFileName);
function onTemplateSelected(templateFileName) {
// Get values from the active sheet and active row
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRowIndex();
var rate = sheet.getLastRow();
var userEmail = sheet.getRange(row, getColIndexByName("Primary Email")).getValue();
var userFullName = sheet.getRange(row, getColIndexByName("Contact Full Name")).getValue();
var userCompanyName = sheet.getRange(row, getColIndexByName("Company Name")).getValue();
var subjectLine = "Company Proposal - " + userCompanyName ;
var aliases = GmailApp.getAliases();
// Create the email template and set values in the template
if (templateFileName == 'Proposal Template.html') {
var proposalTemplate = HtmlService.createTemplateFromFile('Proposal Template.html');
proposalTemplate.userFullName = userFullName;
proposalTemplate.userCompanyName = userCompanyName;
var template = proposalTemplate.evaluate().getContent();
} else if (templateFileName == 'Markting Template') {
var marktingTemplate = HtmlService.createTemplateFromFile('Markting Template.html');
marktingTemplate.userFullName = userFullName;
marktingTemplate.userCompanyName = userCompanyName;
var template = marktingTemplate.evaluate().getContent();
} else {
var template = selectMenuHtml;
}
// Create an HTML output page that displays the email template and a button to send the email
var selectMenu = HtmlService.createTemplateFromFile("template-select-menu.html");
var selectMenuHtml = selectMenu.evaluate().getContent();
var output = HtmlService.createHtmlOutput(template)
.setWidth(600)
.setHeight(450)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setContent(selectMenuHtml + '<br><br>' + template);
// Update the modal dialog box with the new email template
SpreadsheetApp.getUi().showModalDialog(output, 'Email Preview');
}
Now create the the 2 files "Proposal Template.html" and "Markting Template.html". When you switch and click preview the content will change.
Please note that I still need to update the email buttons. but this is a great start for me.

Populating a container with one entry per Firebase entry

I'm using Firebase to store users info and I'm wanting to populate divs with each users info so it can be either accepted or deleted (but not deleted from Firebase).
So I wanted it to be structured something like this:
----------------------
Name
Email
Date
----------------------
Name
Email
Date
----------------------
and so on....
What I'm currently getting back is something like this:
What is the proper way to generate a div dependent upon how much data is in Firebase and format the content as specificed?
HTML:
<div>Some entry here
<h4 id="name"></h4>
<h4 id="date"></h4>
<h6 id="email"></h6>
<button id="0" class="remove">Remove</button>
</div>
<div>Another entry here
<button id="1" class="remove">Remove</button>
</div>
Javascript:
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
$('#name').append(name);
$('#email').append(email);
$('#date').append(date);
});
});
For each child, you are appending the values to the same HTML elements (i.e. all the names are appended to the h4 element with id "name", all the emails to the one with id "email" and so on).
So it is normal they are displayed on a line (one row).
You have to create a new placeholder for each child (and it's set of values). You can do that with e.g. a table, like:
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
// Insert a row in the table at the last row
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell with name value
var newText = document.createTextNode(name); // <-- name value from the child
newCell.appendChild(newText);
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(email); // <-- email value from the child
newCell.appendChild(newText);
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var newText = document.createTextNode(date); // <-- date value from the child
newCell.appendChild(newText);
});
});
Inspired by How to insert row in HTML table body in Javascript?. See the fiddle in this SO post.
Or you can do it with divs, here is a possible code:.
HTML
<div id="parentDiv"></div>
JavaScript
var element;
var ref = firebase.database().ref('requests');
ref.on('value', function(snapshot) {
snapshot.forEach(function(child) {
var datas = child.val();
var email = child.val().Email;
var name = child.val().Name;
var date = child.val().Scheduled_Date;
date = date.replace('.', '/');
element = document.createElement("div");
element.appendChild(document.createTextNode(name));
document.getElementById('parentDiv').appendChild(element);
element = document.createElement("div");
element.appendChild(document.createTextNode(email));
document.getElementById('parentDiv').appendChild(element);
element = document.createElement("div");
element.appendChild(document.createTextNode(date));
document.getElementById('parentDiv').appendChild(element);
//You could add a specific css class to this div to generate the bottom border
});
});
To be complete, note that you could also use some MVVM javascript frameworks like vue.js, knockout.js as well as angular, react... in order to easily reflect in your HTML DOM the results of queries to your backend (and vice-versa).

After refresh the page image is not show in the view in AngularJS?

I have to upload a image in AnguarJS using firebase but problem is that the image is properly uploaded as well as i have to store the imageURL into the localStorage but after refresh the page image is remove i don't uderstand what the problem
$scope.backgroundImageURL = [];
$scope.currentUserObject = {};
$scope.uploadBackgroundImage = function(event) {
//Get the userDetail of the current logged in user
$scope.currentUserObject = localStorage.getItem('userName');
//Get the value from the input field and assign into the fireabse node
var userProductImg = $("#getImageAttribute")[0].files[0];
var PRODUCT_STORAGE_REF = firebase.storage().ref('user/image');
//get the date as well as put the imageURL from node
var rn = new Date().getTime().toString();
var task = PRODUCT_STORAGE_REF.child("loggedInUserObject").child($scope.currentUserObject).child(rn).put(userProductImg).then(function(snapshot) {
$timeout(function(){
$scope.backgroundImageURL.push(snapshot.downloadURL);
localStorage.setItem('userImageURL', $scope.backgroundImageURL);
}, 50);
})
}
<input type="file" id="getImageAttribute" ng-click="$event = $event" ng- model="display" multiple onchange="angular.element(this).scope().uploadBackgroundImage(event)"
/>
<span ng-repeat="imgURL in backgroundImageURL">
<img src="{{imgURL}}">
</span>
?
try using ng-src instead of src attribute as it will refresh the image if the there is a dynamic change in bacground img url.
You can more about this from here: https://www.w3schools.com/angular/ng_ng-src.asp
or
you can try this too : https://docs.angularjs.org/api/ng/directive/ngSrc
After refresh the page, your image array is empty:
$scope.backgroundImageURL = [];
You need a method to get images from the storage and assign them to your backgroundImageURL array, and this method has to be called as soon as you load the page.
Your code might be something like the following:
$scope.backgroundImageURL = [];
$scope.currentUserObject = {};
$scope.loadResources();
$scope.loadResources = function() {
$scope.backgroundImageURL = localStorage.getItem('userImageURL');
$scope.currentUserObject = localStorage.getItem('userName');
}
$scope.uploadBackgroundImage = function(event) {
//Get the userDetail of the current logged in user
$scope.currentUserObject = localStorage.getItem('userName');
//Get the value from the input field and assign into the fireabse node
var userProductImg = $("#getImageAttribute")[0].files[0];
var PRODUCT_STORAGE_REF = firebase.storage().ref('user/image');
//get the date as well as put the imageURL from node
var rn = new Date().getTime().toString();
var task = PRODUCT_STORAGE_REF.child("loggedInUserObject").child($scope.currentUserObject).child(rn).put(userProductImg).then(function(snapshot) {
$timeout(function(){
$scope.backgroundImageURL.push(snapshot.downloadURL);
localStorage.setItem('userImageURL', $scope.backgroundImageURL);
}, 50);
})
}

Javascript (firebase): how can the firebase database key of a clicked item be obtained?

I have a firebase database structure like this
and I have a loop function
var jobTitle = document.getElementById('jobTitle');
var jobDescription= document.getElementById('jobDescription');
firebase.auth().onAuthStateChanged((user) => {
if (user) {
database = firebase.database();
var ref = database.ref('/Jobs/');
ref.on('value', gotData, errData);
}
})
var jobSnap = {};
function gotData(data) {
var date = Today;
var jobs = data.val();
var keys = Object.keys(jobs);
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
for (var i = 0; i<keys.length; i++) {
var k = keys[i];
var newCard = `
<li class="pos-card" id="pos_1">
<div class="content">
<div class="title new">`+jobs[k].JobTitle+`</div>
<div class="dept">Customer Service</div>
<div class="date">date</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>`+jobs[k].JobSummary+`</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
function errData(err) {
console.log('Error!');
console.log(err);
}
This is the function that submits the application to the DB under the respective job id.
function newApplication() {
var database = firebase.database();
var applicant_Name = document.getElementById('name').value;
var applicant_Number = document.getElementById('phone').value;
var applicant_email = document.getElementById('email').value;
var AuthorId = firebase.auth().currentUser.uid;
var cover_letter = document.getElementById('cover_letter').value;
var JobId = jobSnap.key;
var postData = {
ApplicantName: applicant_Name,
ApplicantNumber: applicant_Number,
Applicantemail: applicant_email,
Author: AuthorId,
Cover_letter: cover_letter,
};
var newPostKey = firebase.database().ref().child('Applications').push().key;
var updates = {};
updates['/Applications/' + newPostKey] = postData;
updates[ JobId + '/Applications/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
that retrieves all entries in the database Jobs node and display them like this
When a user clicks the apply button on a job an application fades in; all the code that retrieves the Jobs and application are in the same html file. What I need to do is find a way to capture the firebase job key of the job that was clicked so that i can save the job application under the respective jobs. I have tried many methods but still no luck how can I implement this?
You'll need to keep track of the key of each item in the HTML. A common way to do that is by injecting it into the id attribute in the HTML:
var newCard = `
<li class="pos-card" id="${k}">
Then you can use the id when the user clicks on an element to find the item in the database.
A more idiomatic way to write your code would be:
function gotData(data) {
var date = Today;
var container = document.getElementById('pos_1');
var container2 = document.getElementById('jobapp');
data.forEach(function(jobSnap) { // loop over all jobs
var key = jobSnap.key;
var job = jobSnap.val();
var newCard = `
<li class="pos-card" id="${key}">
<div class="content">
<div class="title new">${job.JobTitle}</div>
<div class="dept">Customer Service</div>
<div class="date">${date}</div>
<div class="refer">Apply</div>
</div>
<ul class="desc">
<li>${job.JobSummary}</li>
</ul>
</li>
`;
container.innerHTML += newCard;
}
}
If the list is dynammic then you can assign it a unique id and add onclick listener
In your JS function,
Function name(value)
{
}

Firebase Javascript: How to create list of value

This is the list of data in my firebase:
This is my source code:
var keys = firebase.database().ref().child('seller').once('child_added').then(function(datakey){
var makeList = firebase.database().ref('seller/' + datakey.getKey() +'/sellerName').once('value').then(function(snapshot){
var nama = snapshot.val();
var button = $(''+ nama + '');
button.appendTo('#sellerList');
});
});
My problem is, when I execute it, it only create a button element for Seller Name 'Miraak' only but not 'Khajiit'. Like this:
I want it to create a list of buttons based on the number of seller in my firebase. Like currently I have two seller, Miraak and Khajiit, I want both of them to appear as button list.
var keys = firebase.database().ref().child('seller/').once('value').then(function(datakey){
datakey.forEach(function(data){
var nama = data.val();
var button = $(''+ nama.sellerName + '');
button.appendTo('#sellerList');
});
});
Nevermind, I found the solution to my problem. Thank you.

Categories

Resources