Making web form for updating data in Firebase - javascript

I am making an interface to manipulate data in Firebase. I managed to make a form that inserts new data, I have a list of retrieved data, the only thing that is missing is editing/updating existing data.
I am using Foundation 6 to speed up coding HTML and CSS and I created a modal that pops up when you click on a name. Also, I made that every name has a class that is their child key in Firebase so I can open data for the right item. I've stuck here and I don't know how to make that form in modal to fill data from clicked name. Can somebody help me a bit?
Here is my code:
var ref = new Firebase("https://myname.firebaseio.com/data/users");
ref.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + "\">" + "<a data-open=\"modal\">" + name + ", " + city + "</a></li>"));
// this is for filling up the form with loaded data
$(".name").val(name);
$(".name").focus(function(){
$(this).val(name);
});
});

Try this:
var ref = new Firebase("https://myname.firebaseio.com/data/users");
var data;
ref.on('value', function(snapshot) {
data = snapshot.val();
$("#results").empty();
Object.keys(data).forEach(function(key) {
var value = data[key];
var name = value.name;
var city = value.city;
var li = $("<li class=\"" + key + "\">" + "<a data-open=\"modal\">" + name + ", " + city + "</a></li>");
$("#results").append(li);
li.click(function() {
$('#name').val(name);
$('#city').val(city);
$('#key').val(key);
});
});
});
$('form').submit(function() {
var key = $('#key').val();
var name = $('#name').val();
var city = $('#city').val();
data[key].name = name;
data[key].city = city;
ref.set(data);
return false;
});
JSFIDDLE

Related

Not pulling any data from JQuery object

$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>

How to retreive data from Firebase with JavaScript

I am trying to retrieve some data from Firebase using JavaScript, but I have a problem. I can't get the items of my child "Usuarios".
This is how my database looks like
var rootRef = firebase.database().ref().child("Usuarios");
rootRef.on("child_added", snap => {
var name = snap.child("Nombre").val();
var email `enter code here`= snap.child("Apellido").val();
$("#table_body").append("<tr><td>" + name + "</td><td>" + email + "</td><td><button>Remove</button></td></tr>");
});
what #hazelcodes said, It would look something like this
var rootRef = firebase.database().ref().child("netflixfirebase-568e8/Usuarios");
I´ve got a solution, I added the function "childSnapshot"to the "Snapchot" that I already had.I checked each element (that is an Object) and took the properties they contained.
The code here:
var ref = firebase.database().ref ().child("Usuarios/");
ref.on("value", function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
var keystl = Object.keys(childData);
console.log(childData);
console.log(keystl);
for (var i = 0; i < keystl.length; i++)
{
var k = keystl[i];
var nombre = childData[k].Nombre;
var apellido = childData[k].Apellido;
console.log(nombre, apellido);
$("#table_body").append("<tr><td>" + nombre + "</td><td>" + apellido + "</td><td><button>Remove</button></td></tr>");
}
});
});

Retriving data from firebase web

I am trying to fetch the data for website using java script. Problem I am getting is that I am unable to get the key of Users-->history-->location-->from-->(lat,lng). I am unable to find a syntax of it.
Code I am trying is
var ref = firebase.database().ref("history/" + keys +"/location/from");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
//console.log(data.val());
var from = data.val();
var keys=Object.keys(from);
console.log(keys);
for(var i=0 ; i<keys.length;i++)
{
var k=keys[i];
var name = from[k].customer;
var phone = from[k].driver;
//console.log(name,phone,imag);
$('ul').append( '<li>' + name +" : " + phone+ '</li>' );
}
}
This should print the lat and lng of each item in the history:
var ref = firebase.database().ref("history/");
ref.on('value',gotDataa,errDataa);
function gotDataa(data){
data.forEach(function(child) {
var from = data.val().location.from;
console.log(from.lat+","+from.lng);
});
}

SharePoint working with lookup dropdowns and getting values

I seem to have a little trouble getting a value to be returned from a dropdown lookup field. I've got the following code that gets me the values from the list I'm doing the lookup upon:
var siteUrl = _spPageContextInfo.webServerRelativeUrl;
function getDropdownValues(tempNumTitle) {
var clientContext = new SP.ClientContext(siteUrl);
var tempDropdownValueList = clientContext.get_web().get_lists().getByTitle('Temps');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<RowLimit>' +
'100' +
'</RowLimit>' +
'</View>');
this.tempQuery = tempDropdownValueList.getItems(camlQuery);
clientContext.load(tempQuery);
clientContext.executeQueryAsync(
// on success of getting Temp Values from dropdown
// match it with the tempNum entry
function (sender, args) {
var tempDropDownValues = {};
var tempEnumerator = tempQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
var tempTitle = tempItem.get_item('Title');
var tempId = tempItem.get_item('ID');
tempDropDownValues[tempTitle] = tempId;
}
selectTemp(tempNumTitle, tempDropdownValues)
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It performs this fine, giving me the dropdown values. It then calls the function selectTemp with the parameters of the tempNumTitle we are looking for, and the list of dropdown values retrieved. Here is the next function:
function selectTemp(tempNumTitle, tempValues) {
var clientContext = new SP.ClientContext(siteUrl);
var tempMatchValueList = clientContext.get_web().get_lists().getByTitle('Numbers-Temp');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<Query>' +
'<Where>' +
'<Eq>' +
'<FieldRef Name="Title" />' +
'<Value Type="Text">' + tempNumTitle + '</Value>' +
'</Eq>' +
'</Where>' +
'</Query>' +
'</View>');
this.tempMatchValueQuery = tempMatchValueList.getItems(camlQuery);
clientContext.load(tempMatchValueQuery);
clientContext.executeQueryAsync(
// on success
function (sender, args) {
var temp = '';
tempEnumerator = tempMatchValueQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
temp = tempItem.get_item('Temp0');
}
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It almost gets me what I'm looking for, but I get something like this:
temp: {$1E_1: 3, $2e_1: "Temp 3"}
Where I want the value of the $2e_1, or "Temp 3". How can I get that value, without just going temp["$2e_1"]?
When accessing a lookup column or a people picker column, the column value is a complex type rather than a simple string.
You can invoke .get_lookupValue() on the returned object to get a text representation of the lookup column's value, or .get_lookupId() to get the ID number of the corresponding item in the lookup list (or in the site collection's user information list in the case of a people picker column).
So in your case, assuming "Temp0" is the internal name of a lookup column, you should be able to do this:
temp = tempItem.get_item('Temp0').get_lookupValue();

Changing the objectId thats returned in a query to that of the actual user

Using parse.com and JavaScript SDK.
This is what I'm attempting to achieve.
A list of users (friends) is returned on the page to the user, They can then click on one of these users and the page is updated to list all of that users items (which are basically images).
This query works correctly and returns a list of users.
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper" data-friend-request-id="' + item.friendRequestId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
****This below query should contain the user who has selected above and stored in window.selectedFriendRequestId (which is saved in the variable friendRequest ****
This query looks at the myBadges class and the user reference "SentTo" the ref used is for example a3aePaphBF which is the actual _User objectID.
function FriendProfile() {
var friendRequest = "window.selectedFriendRequestId";
console.log(window.selectedFriendRequestId);
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", friendRequest);
query.find({
success: function (results) {
// If the query is successful, store each image URL in an array of image URL's
imageURLs = [];
for (var i = 0; i < results.length; i++) {
var object = results[i];
imageURLs.push(object.get('BadgeName'));
}
// If the imageURLs array has items in it, set the src of an IMG element to the first URL in the array
for (var j = 0; j < imageURLs.length; j++) {
$('#imgs').append("<img src='" + imageURLs[j] + "'/>");
}
},
error: function (error) {
// If the query is unsuccessful, report any errors
alert("Error: " + error.code + " " + error.message);
}
});
}
The issue is that the first query is not returning an objectId that I can use in the second query as a reference. For example a3aePaphBF is not returned but cr3LG70vrF is.
How to I return the actual _User objectid in the first query so I can make these match?
To get the ID of a user:
results[i].get('toUser').id
So if you update your section of code that is doing friends.push(...):
friends.push({
imageURL: results[i].get('toUser').get('pic'),
friendRequestId: results[i].id,
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
Then in your bit where you create the wrapper:
_.each(friends, function (item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div class="wrapper"'
+ ' data-friend-request-id="' + item.friendRequestId + '"'
+ ' data-to-user-id="' + item.userId + '"></div>');
wrapper.append('<img class="images" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.username + '</div>');
$('#container').append(wrapper);
});
Notice that I've added another data-property to hold the ID of the toUser.
Now if you followed the tips from your other question, you can tweak the code that attaches the on-click handler to pass toUserId also:
$('#container').on('click', '.wrapper', function () {
var wrapper = $(this);
var friendRequestId = wrapper.data('friendRequestId');
var toUserId = wrapper.data('toUserId');
FriendProfile(friendRequestId, toUserId);
// other code ...
});
Lastly your FriendProfile() function can now use either of those parameters as needed:
function FriendProfile(friendRequestId, toUserId) {
var toUser = new Parse.User();
toUser.id = toUserId;
var myBadges = Parse.Object.extend("myBadges");
var query = new Parse.Query(myBadges);
query.equalTo("SentTo", toUser);
// ... etc ...
}
NOTE: The User class should be locked down for privacy reasons, you shouldn't be able to read any properties of other users except in Cloud Code when you have the following line in your Cloud Function:
Parse.Cloud.useMasterKey();

Categories

Resources