Add and update var time to realtime Firebase - javascript

Hello, I'm still a beginner in firebase, honestly I'm a bit confused hehehe, btw I want to add a time variable to realtime firebase and it will be updated every time the data changes.
Btw this is my code, I don't know what's next.
Thank you.
enter image description here
<script>
// Initialize Firebase
var firebaseConfig = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxx",
projectId: "xxxxxxxxxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxx"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var times = h + ":" + m;
var database = firebase.database();
database.ref('Time').set({
Recent: times
});
}
</script>

Related

Adding Firebase to JavaScript Project

I'm trying to programm a Chat Web-Application with Firebase. I am using HTML as a return method in Javascript. I tried to include my DB Firebase but I'm getting an error, that the DB is not defined. Can someone solve my Problem?
function Chats() {
const username = prompt("What's your name?");
document.getElementById("send-message").addEventListener("submit", postChat);
function postChat(e) {
e.preventDefault();
const timestamp = Date.now();
const chatTxt = document.getElementById("chat-txt");
const message = chatTxt.value;
chatTxt.value = "";
db.ref("messages/" + timestamp).set({
usr: username,
msg: message,
});
}
return (
<div id="chat">
<ul id = "messages"></ul>
<form id="send-messages">
<input id="chat-txt" type= "text"></input>
<button id="chat-btn">Submit</button>
</form>
<script src="https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js"></script>
<script src="https://united-parents-default-rtdb.europe-west1.firebasedatabase.app"></script>
</div>
);
}
declare DB variable at start of your script
var db = firebase.database();
first you have to initialize the firebase
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-functions.js"></script>
<script>
var firebaseConfig = {
apiKey: "api_key",
authDomain: "authDomain",
databaseURL: "databaseURL",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"
};
firebase.initializeApp(firebaseConfig);
</script>
you can get this from firebase console as well

How can I retrieve data from my firebase database?

I have tried many ways to get data from my firebase database, but they dont work.
Is there any simple way to retrieve data from my firebase database?
my js code:
var firebaseConfig = {
apiKey: "REDACTED",
authDomain: "REDACTED.firebaseapp.com",
projectId: "REDACTED",
storageBucket: "REDACTED.appspot.com",
messagingSenderId: "474155068193",
appId: "REDACTED",
measurementId: "G-715TVNY07N"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('en');
function lah(){
var data = {
kommentti: document.getElementById("viesti").value
}
ref.push(data);
}
my database:
I would like to know what is inside those kommenttis.
If you want to get the data just once without a listener you can use a function like this one:
const getData = async () => {
return firebase
.database()
.ref("en")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const kommentti = childData.kommentti;
});
});
};

Firebase initialization

I am using Firebase for the back-end of my app, my firebase configuration looks like :
const firebaseConfig = {
apiKey: 'xx',
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
}
firebase.initializeApp(firebaseConfig)
my question is what if i some configuration data is incorrect.
So how to check if my Firebase database is initialized correctly ? thanks
You can write a test case to check if your configuration is valid.
const getPost = async () => {
const snapshot = await firestore.collection('Posts').get();
const myPosts = snapshot.docs.map(collectIdsAndDocs);
console.log(myPosts);
setPosts({ myPosts });
};
const createPost = async (post) => {
const docRef = await firestore.collection('Posts').add(post);
const doc = await docRef.get();
console.log(doc);
};
createPost({ Title: 'My First Post', Content: 'My content' });
getPost();

Firebase Auth to sign-in google not working in Framework7

I have setup Firebase admin structure and generate all required id, key and token. With Firebase email and password auth it works fine. But when implementing Google signin it fails. Please help.
index.html code
`<i class="icon fab fa-google-plus-g"></i>`
<script src="js/firebase.js"></script>
<script src="js/firebase-auth.js"></script>
<script>
// Initialize Firebase
var configfirebase = {
apiKey: "***********************",
authDomain: "*****************.firebaseapp.com",
databaseURL: "https://f*************.firebaseio.com",
projectId: "************",
storageBucket: "************",
messagingSenderId: "**********",
};
firebase.initializeApp(configfirebase);
</script>
registration.js code
var provider = new firebase.auth.GoogleAuthProvider();
function firebaselogin() {
firebase.auth().signInWithRedirect(provider).then(function() {
return firebase.auth().getRedirectResult();
}).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
app.dialog.alert('Login success!! Welcome:' + result.user );
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
app.dialog.alert('Login error!! error:' + errorMessage );
});
}
When I run the app I get this error.
I have fixed that issue by just placing the firebase-app js to top.

Retrieve firebase data to web

// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
I continue getting this error [Uncaught TypeError: firebase is not a function] as i am trying to read firebase data to web.
Chrome console error
here's how your code must be:
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on("child_added",function(snapshot) {
var changedPost = snapshot.val();
console.log(changedPost)
});
</script>
The code above works as you expect:
Note that msgRef listens on these predefined "events".
Details here: Read Event Types
Regards
Change this:
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
to this:
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on('value', function(snapshot) {
//retrieve data
});

Categories