I managed to successfully call a function whenever a page is scrolled to its maximum, but I don't know how to make that function call the data from the database and them in the correct order. Here is my current code:
function loadMoreData(num) {
var rawDataRef = db.ref("chat/"+group);
rawDataRef.on("value", function(data) {
if (data.hasChildren() == true) {
var uid = firebase.auth().currentUser.uid;
var keys = Object.keys(data.val());
var startAt = keys[num-1];
var dataRef = db.ref("chat/"+group+"/").startAt(startAt).limitToLast(15);
dataRef.on("value", function(snapshot) {
var data = snapshot.val();
var keys = Object.keys(data);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
if (data[k].uid == uid) {
$("#data").prepend('<div class="dataByMe">'+data[k].data+'</div><br><br>');
} else if (data[k].uid != uid) {
$("#data").prepend('<div class="dataByOthers">'+data[k].data+'</div><br><br>');
}
}
});
}
});
}
My code shows the last 25 data when the page is first loaded, and then, when the page is scrolled to the top, I need to load 15 more data before the point where the last 25 data starts, and show them in the order of latest data at the bottom. How exactly do I do this?
Note: The dataByMe and dataByOthers classes are because I need to style them differently.
Related
I have two products on my product table in firebase. Here it is:
Now I want to update product_quantity when the user takes action. But when the user chooses two or more products and inputs the quantity of chosen products, only the last product quantity got replaced or updated. product selection view looks like this:
And 2nd product selection looks like this:
Here is the code for javascript:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
for (var i = 0; i < itemCnt; i++) {
var uidValueInv = $(".item-wrapper").eq(i).find(".uidVal").val();
var productNameInv = $(".item-wrapper").eq(i).find(".productName").val();
var amountInv = parseFloat($(".item-wrapper").eq(i).find(".amount").val());
var sellingPriceInv = parseFloat($(".item-wrapper").eq(i).find(".sellPrice").val());
var buyingPriceInv = parseFloat($(".item-wrapper").eq(i).find(".buyPrice").val());
var quantityInv = parseFloat($(".item-wrapper").eq(i).find(".quantity").val()) || 0;
var quantityCount = amountInv - quantityInv;
console.log(quantityCount)
var query = firebase.database().ref("Products/").child(uid).
orderByChild("uid").equalTo(uidValueInv);
query.once("child_added", function(snapshot) {
snapshot.ref.update({
product_quantity: quantityCount.toString()
})
})
}
})
I uploaded here only firebase code, not the entire javascript how product_quantity and other stuff calculate, because those things work perfectly I checked the console that got the product_quantity perfectly. I think I just need to change in firebase update code.
I change below code:
firebase.database().ref('Products/').child(uid).once('value').then(function (snapshot)
{
for (var i = 0; i < itemCnt; i++) {
var uidValueInv = $(".item-wrapper").eq(i).find(".uidVal").val();
console.log(uidValueInv);
var amountInv = parseFloat($(".item-wrapper").eq(i).find(".amount").val());
var quantityInv = parseFloat($(".item-wrapper").eq(i).find(".quantity")
.val()) || 0;
var quantityCount = amountInv - quantityInv;
console.log(quantityCount)
snapshot.forEach(function (childSnapshot) {
var uid_value = childSnapshot.child('uid').val();
console.log(uid_value)
if (uid_value === uidValueInv) {
childSnapshot.ref.update({
product_quantity: quantityCount.toString()
});
}
})
}
})
I have problem editing local storage data. I saved Array of Array-list in local storage and it works, or save. However, when i tried to edit, it only edit temporarily and the edited data disappear when i refresh the page and it shows the original data i saved
function editinfo(){
var name = document.getElementById("nameB").value;
var price = document.getElementById("priceB").value;
var quant = document.getElementById("quantityB").value;
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for (i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1]= price
pro[i][2] = quant;
} else{
console.log("There is no such data to edit");
}
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
// I saved information on local storage, I read data from server.
var bevInventory = $.getJSON('http://pub.jamaica-inn.net/fpdb/api.php?username=jorass&password=jorass&action=inventory_get');
function Info(){
var info = [];
bevInventory.done(function(result){
for(i = 0; i < result.payload.length; ++i){
if(result.payload[i].namn != ""){
var makeList = [result.payload[i].namn, result.payload[i].price, result.payload[i].count];
info.push(makeList);
}
}
var xx = window.localStorage.setItem("done", JSON.stringify(info));
})
return info;
}
One solution is to check first, and add data to local storage if it does not exist. Like this
function editinfo() {
var name = 'bob';
var price = 1;
var quant = 2; // loaded dynamically from page.
if (window.localStorage.hasOwnProperty("done")) {
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for(i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1] = price
pro[i][2] = quant;
}
}
} else {
pro = [[name, price, quant]];
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
Your code fails if there is no "done" data initially in localStorage. JSON.parse() parses null (because of no data) and then error occurs on line
pro.length
So it's better to check if it's a first launch and there is no data:
if (!pro) {
pro = [];
}
Example here
After first executing of editinfo() data successfully saves in localStorage.
so when trying to go through a loop that checks, updates, and posts data to my Firebase storage, it seems that whenever I try to use the Firebase.update(), then it messes with my for loop and it repeats incrementations or doesn't increment at all. Any advice?
My Code:
var j = 0;
var k = 0;
var l = 0;
var m = 0;
var setDict = {};
for(var h = 0; h < teamWinNames.length; h++)
{
console.log(j);
console.log(h);
console.log(meWinList[j]);
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
var tempName = teamWinNames[h];
tempRef.once("value", function (teamWinSnapshot)
{
var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
console.log(exists);
if(exists == true)
{
console.log("Here");
var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
console.log(tempVal);
//var tempValue = obj[tempname][tempchamp];
//console.log(tempValue);
}
else
{
setDict[tempName] = '1-0-0-0';
console.log(setDict);
}
});
if(h != 0 && (h+1)%4 == 0)
{
sendUpdate(setDict, meWinList[j], username);
setDict = {};
j++;
}
}
and the function that makes the update:
function sendUpdate(data, champ, username)
{
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
tempRef.child(champ).update(data);
}
The problem is that you are getting your data in the for loop and also changing it inside the loop. This means that the data you are using in your loop changes with each iteration. And as an added bonus you get the effects of the asynchronous nature of firebase that can look something like this:
Get data (1)
Get data (2)
Update data (1)
Get data (3)
Update data (3)
Update data (2)
To prevent all this i suggest putting the for loop inside the tempRef.once function like this: (pseudo code)
tempRef.once{
Loop through data{
Change data
}
Update data
}
This means you only have to get the data once and update it once.
I have some code like this:
var data = // coming in from AJAX and confirmed working, don't need to wory about this...
var row = // cloning an existing HTML structure in the DOM
for (i = 0; i < data.length; i++) {
var rowclone = row.clone();
var orderLastChangedTime = new Date(data[i].createDate);
var diffDays = Math.round(Math.abs((currentTime.getTime() - orderLastChangedTime.getTime())/(oneDay)));
rowclone.find(".home-order-calc").text(diffDays);
rowclone.find(".home-order-status").text(data[i].status);
rowclone.find(".home-order-po-number").text(data[i].poNumber);
rowclone.find(".home-order-number").text(data[i].orderId);
rowclone.find(".home-order-last-changed").text(orderLastChangedTime);
rowclone.find(".home-order-lines").text(data[i].itemsCount);
rowclone.find(".home-order-cost").text(data[i].cost);
var rowstatus = rowclone.find(".home-order-status").text();
rowstatus = rowstatus.toUpperCase();
openJSONitems = [];
closedJSONitems = [];
otherJSONitems = [];
if (status[rowstatus] == "open") {
openJSONitems.push(rowclone);
}
else if (status[rowstatus] == "closed") {
closedJSONitems.push(rowclone);
}
else {
otherJSONitems.push(rowclone);
}
console.log(openJSONitems);
openJSONitems.appendTo("#home-table-orders");
}
I am trying to create 3 new JavaScript arrays and array push data into them based on sort criteria from the JSON payload. Once they are sorted I want to hang on to them and attach them to the DOM on some user actions... what am I doing wrong?
openJSONitems is an array, it doesn't have the appendTo method, you'll have to iterate over that array and append its elements to "#home-table-orders". Besides, you're creating a new array in each iteration. I think this changes would fix the problem. You could also avoid the last loop inserting the element directly when status[rowstatus] == "open" if you liked.
var openJSONitems = [],
closedJSONitems = [],
otherJSONitems = [];
var data = // coming in from AJAX and confirmed working, don't need to wory about this...
var row = // cloning an existing HTML structure in the DOM
for (i = 0; i < data.length; i++) {
var rowclone = row.clone();
var orderLastChangedTime = new Date(data[i].createDate);
var diffDays = Math.round(Math.abs((currentTime.getTime() - orderLastChangedTime.getTime())/(oneDay)));
rowclone.find(".home-order-calc").text(diffDays);
rowclone.find(".home-order-status").text(data[i].status);
rowclone.find(".home-order-po-number").text(data[i].poNumber);
rowclone.find(".home-order-number").text(data[i].orderId);
rowclone.find(".home-order-last-changed").text(orderLastChangedTime);
rowclone.find(".home-order-lines").text(data[i].itemsCount);
rowclone.find(".home-order-cost").text(data[i].cost);
var rowstatus = rowclone.find(".home-order-status").text();
rowstatus = rowstatus.toUpperCase();
if (status[rowstatus] == "open") {
openJSONitems.push(rowclone);
}
else if (status[rowstatus] == "closed") {
closedJSONitems.push(rowclone);
}
else {
otherJSONitems.push(rowclone);
}
}
console.log(openJSONitems);
for (i = 0; i < openJSONitems.length; i++) {
$(openJSONitems[i]).appendTo("#home-table-orders");
}
You could add then as a data element onto a DOM object.
$('body').data('openItems', openJSONitems);
And retrieve them later:
var items = $('body').data('openItems');
Have you considered using localStorage?
localStorage.setItem('openJSONitems', openJSONitems );
And retrieving it with...
var openJSONitems = localStorage.getItem('openJSONitems');
How to increase the numerical value of 3rd column in a particular row when some one click on the link which is in the 2nd column of same row? Data loads from firebase in tabular form.
Fiddle here, so you can understand it much better.
The script which loads (callback) data from firebase is given bellow
var LEADERBOARD_SIZE = 10;
var get_title = $('title').html();
var get_id = $('id').find('textarea').html();
// Create our Firebase reference
var scoreListRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
// Keep a mapping of firebase locations to HTML elements, so we can move / remove elements as necessary.
var htmlForPath = {};
// Helper function that takes a new score snapshot and adds an appropriate row to our leaderboard table.
function handleScoreAdded(scoreSnapshot, prevScoreName) {
var newScoreRow = $("");
newScoreRow.append($("").append($("").text(scoreSnapshot.val().name)));
newScoreRow.append($("").text(scoreSnapshot.val().url));
newScoreRow.append($("").text(scoreSnapshot.val().score));
// Store a reference to the table row so we can get it again later.
htmlForPath[scoreSnapshot.name()] = newScoreRow;
// Insert the new score in the appropriate place in the table.
if (prevScoreName === null) {
$("#leaderboardTable").append(newScoreRow);
} else {
var lowerScoreRow = htmlForPath[prevScoreName];
lowerScoreRow.before(newScoreRow);
}
}
// Helper function to handle a score object being removed; just removes the corresponding table row.
function handleScoreRemoved(scoreSnapshot) {
var removedScoreRow = htmlForPath[scoreSnapshot.name()];
removedScoreRow.remove();
delete htmlForPath[scoreSnapshot.name()];
}
// Create a view to only receive callbacks for the last LEADERBOARD_SIZE scores
var scoreListView = scoreListRef.limit(LEADERBOARD_SIZE);
// Add a callback to handle when a new score is added.
scoreListView.on('child_added', function (newScoreSnapshot, prevScoreName) {
handleScoreAdded(newScoreSnapshot, prevScoreName);
});
// Add a callback to handle when a score is removed
scoreListView.on('child_removed', function (oldScoreSnapshot) {
handleScoreRemoved(oldScoreSnapshot);
});
// Add a callback to handle when a score changes or moves positions.
var changedCallback = function (scoreSnapshot, prevScoreName) {
handleScoreRemoved(scoreSnapshot);
handleScoreAdded(scoreSnapshot, prevScoreName);
};
scoreListView.on('child_moved', changedCallback);
scoreListView.on('child_changed', changedCallback);
// When the user presses enter on scoreInput, add the score, and update the highest score.
$("#scoreInput").keypress(function (e) {
if (e.keyCode == 13) {
var newScore = ($("#scoreInput").val());
var url1 = $("#urlInput").val();
var name = $("#nameInput").val();
$("#scoreInput").val("");
if (url1.length === 0)
if (name.length === 0) return;
var userScoreRef = scoreListRef.child(name);
// Use setWithPriority to put the name / score in Firebase, and set the priority to be the score.
userScoreRef.setWithPriority({
name: name,
url: url1,
score: newScore
}, newScore);
alert('Alternate Link for this App has been Succesfully submitted by you. By using this service you agree that you will Not Spam or Submit Links which refers to illegal or Copyrighted content.');
}
});
// delay function to make link clickable after 4 sec and also add onclick='HitCounter()' into links
var delay = 4000 //4 seconds
setTimeout(function () {
function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])/ig;
return text.replace(re, function (match, lParens, url) {
var rParens = '';
lParens = lParens || '';
var lParenCounter = /\(/g;
while (lParenCounter.exec(lParens)) {
var m;
if (m = /(.*)(\.\).*)/.exec(url) || /(.*)(\).*)/.exec(url)) {
url = m[1];
rParens = m[2] + rParens;
}
}
return lParens + "" + url + "" + rParens;
});
}
var elm = document.getElementById('leaderboardTable');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
$(document).ready(function () {
$("a[href^='http://']").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
});
}, delay)
and the script which take care of URL Hit Counts is given bellow
function HitCounter() {
var get_id = $('id').find('textarea').html();
var HitCounterRef = new Firebase('https://androidappania.firebaseio.com//AlternateLinksDirectory//' + get_id);
var hits = $(tbody).find('tr').children('td').html();
if (hits == null) {
hits = 1;
} else {
hits++;
}
HitCounterRef.setWithPriority({
score: hits
}, hits);
};
I need some modification or improvement in this code so that when some one click on a link then correct corresponding 3rd column of same row should get a increment/increase in it's numerical value.
I also need something which could create connection b/w HitCounter and urls given in 2nd column of every row or initiate the HitCounter function when some one click on any of the link given in 2nd column of every row.