Last active
May 10, 2021 08:55
-
-
Save dvidsilva/e000acc9610b21e43e0a58e5982bd6e9 to your computer and use it in GitHub Desktop.
HTMLForm to Firebase sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var newscript = document.createElement('script'); | |
newscript.type = 'text/javascript'; | |
newscript.async = true; | |
newscript.src = 'https://www.gstatic.com/firebasejs/3.0.2/firebase.js'; | |
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript); | |
})(); | |
_setFormData = function setFormData (sel, data) { | |
console.info('setting form to data', data); | |
var inputList = document.querySelectorAll(sel + ' [name]'); | |
[].forEach.call(inputList, function(input) { | |
console.log(input); | |
if (data[input.name] && data[input.name] !== "undefined") { | |
input.value = data[input.name]; | |
} | |
}); | |
}; | |
var _fb; | |
var fbToForm = function fbToForm (key, sel) { | |
var config = config || { | |
apiKey: "<REPLACE ME>", | |
authDomain: "<REPLACE ME>", | |
databaseURL: "<REPLACE ME>", | |
storageBucket: "<REPLACE ME>", | |
}; | |
_fb = _fb && _fb.name === "fbToForm" ? _fb : firebase.initializeApp(config, "fbToForm"); | |
_fb.database().ref('user-data/' + key).on('value', function(snapshot) { | |
_setFormData(sel, snapshot.val()); | |
}); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> | |
<title>Firebase Sample</title> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="page-header"> | |
<h1>Firebase Sample</h1> | |
</div> | |
</div> | |
<div class="container row"> | |
<div class="col-xs-12"> | |
<h2>Instructions:</h2> | |
<ul> | |
<li>Create a firebase application on the <a href="https://console.firebase.google.com" target="blank">console</a></li> | |
<li>Replace the information marked as <REPLACE ME> with the correct information from the project's console</li> | |
</ul> | |
<h2>Todo:</h2> | |
<p><strong><a href="https://www.firebase.com/docs/web/guide/user-auth.html">Add User Login</a></strong></p> | |
<p><strong><a href="https://www.firebase.com/docs/security/guide/user-security.html">Add Security Rules</a></strong></p> | |
</div> | |
</div> | |
<div class="container row"> | |
<div class="col-xs-12"> | |
<div class="form"> | |
<form action="" class="form"> | |
<div class="control-group"> | |
<label for="first_name">Name</label> | |
<input type="text" name="first_name"> | |
</div> | |
<div> | |
<button class="submit btn btn-primary">Save</button> | |
</div> | |
</form> | |
</div> | |
</div> | |
</div> | |
<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script> | |
<script> | |
$.fn.getFormData = function() { | |
var fields = this.find('[name]'); | |
var result = {}; | |
$.each(fields, function (i, el) { | |
result[el.name] = el.value; | |
}); | |
return result; | |
}; | |
var config = { | |
apiKey: "<REPLACE ME>", | |
authDomain: "<REPLACE ME>", | |
databaseURL: "<REPLACE ME>", | |
storageBucket: "<REPLACE ME>", | |
}; | |
var fb = firebase.initializeApp(config); | |
var user_id; | |
$('.submit').on('click', function (e) { | |
e.preventDefault(); | |
var updates = {}; | |
user_id = user_id ? user_id : fb.database().ref().child('user-data').push().key; | |
updates[user_id] = $('form').getFormData(); | |
fb.database().ref().child('user-data').update(updates); | |
}); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// ************************************************
// Initialize Firebase
var config = {
apiKey: "AIzaSyBICyFq4GPWKBhCNe46-1MCsDNbfoymkU0",
authDomain: "amazing-project-95629.firebaseapp.com",
databaseURL: "https://amazing-project-95629.firebaseio.com",
projectId: "amazing-project-95629",
storageBucket: "amazing-project-95629.appspot.com",
messagingSenderId: "42388728204"
};
firebase.initializeApp(config);
var database = firebase.database();
// ************************************************
var shoppingCart = (function() {
// =============================
// Private methods and propeties
// =============================
cart = [];
// Constructor
function Item(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
// Save cart
function saveCart() {
sessionStorage.setItem('shoppingCart', JSON.stringify(cart));
}
function loadCart() {
cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
}
if (sessionStorage.getItem("shoppingCart") != null) {
loadCart();
}
// =============================
// Public methods and propeties
// =============================
var obj = {};
// Add to cart
obj.addItemToCart = function(name, price, count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
saveCart();
return;
}
}
var item = new Item(name, price, count);
cart.push(item);
saveCart();
};
// Set count from item
obj.setCountForItem = function(name, count) {
for(var i in cart) {
if (cart[i].name === name) {
cart[i].count = count;
break;
}
}
};
// Remove item from cart
obj.removeItemFromCart = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count --;
if(cart[item].count === 0) {
cart.splice(item, 1);
}
break;
}
}
saveCart();
};
// Remove all items from cart
obj.removeItemFromCartAll = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart.splice(item, 1);
break;
}
}
saveCart();
};
// Clear cart
obj.clearCart = function() {
cart = [];
saveCart();
};
// Count cart
obj.totalCount = function() {
var totalCount = 0;
for(var item in cart) {
totalCount += cart[item].count;
}
return totalCount;
};
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
};
// List cart
obj.listCart = function() {
var cartCopy = [];
for(i in cart) {
item = cart[i];
itemCopy = {};
for(p in item) {
itemCopy[p] = item[p];
};
// cart : DataRef
// Item : Object/Class
// addItemToCart : Function
// removeItemFromCart : Function
// removeItemFromCartAll : Function
// clearCart : Function
// countCart : Function
// totalCart : Function
// listCart : Function
// saveCart : Function
// loadCart : Function
return obj;
})();
// *****************************************
// Triggers / snapshots
// *****************************************
// Add item
database.ref('.add-to-cart').click(function(snapshot) {
snapshot.prsnapshotDefault();
var name = database.ref(this).data('name');
var price = Number(database.ref(this).data('price'));
shoppingCart.addItemToCart(name, price, 1);
displayCart();
});
// Clear items
database.ref('.clear-cart').click(function() {
shoppingCart.clearCart();
displayCart();
});
function displayCart() {
var database = firebase.database().ref().child('Tasks');
var cartDataRef = shoppingCart.listCart();
var output = "";
for(var i in cartDataRef) {
output += ""
+ "" + cartDataRef[i].name + ""
+ "(" + cartDataRef[i].price + ")"
+ "
+ ""
+ "+
+ "X"
+ " = "
+ "" + cartDataRef[i].total + ""
+ "";
}
database.ref('.show-cart').html(output);
database.ref('.total-cart').html(shoppingCart.totalCart());
database.ref('.total-count').html(shoppingCart.totalCount());
}
// Delete item button
database.ref('.show-cart').on("click", ".delete-item", function(snapshot) {
var name = database.ref(this).data('name');
shoppingCart.removeItemFromCartAll(name);
displayCart();
});
// -1
database.ref('.show-cart').on("click", ".minus-item", function(snapshot) {
var name = database.ref(this).data('name');
shoppingCart.removeItemFromCart(name);
displayCart();
});
// +1
database.ref('.show-cart').on("click", ".plus-item", function(snapshot) {
var name = database.ref(this).data('name');
shoppingCart.addItemToCart(name);
displayCart();
});
// Item count input
database.ref('.show-cart').on("change", ".item-count", function(snapshot) {
var name = database.ref(this).data('name');
var count = Number(database.ref(this).val());
shoppingCart.setCountForItem(name, count);
displayCart();
});
displayCart();