how can I make a router system with crossroads.js where if I go to for example this URL: localhost/user/{{username}} then get the details of that user there's entered in the URL with firebase.
get user detail once :
var database = firebase.database();
var route1 = crossroads.addRoute('/user/{username}', function(id){
firebase.database().ref('/user/' + id).once('value').then(function(snapshot) {
var username = snapshot.val().username;
// ...
});
});
Related
I am trying to make a login form but there is a problem.The system is;If a user exists with that password and email;System is going to store the email value and password value as session.After that
I want the system route user to /searchpage.
how can i do this ?
app.post("/Logincheck",function(req,res){
var route;
var login_email_input=req.body.email_input;
var login_password_input=req.body.password_input;
var query="SELECT COUNT(*) FROM users WHERE Email_value='emailx' AND Password='passwordx'";
var query_2=query.replace("emailx",login_email_input);
var query_3=query_2.replace("passwordx",login_password_input);
server.query(query_3,function(error,fields,result){
if(error){
throw error;
}
else{
var row=result[0]["COUNT(*)"];
if(row==0){
res.send("<script>alert('The user is not found.Please try again.')</script>");
}
else{
var sess=req.session;
session.email=login_email_input;
session.password=login_password_input;
route="/searchpage";
}
}
You can use the method : res.redirect(route) to route the user to the Searchpage after a successful login
I want only one announce my firebase database reference object
so I try this....
index.php
(javascript)
var auth, database, userInfo;
var Attendances_monthlyRef, Attendances_dailyRef, UsersRef;
database = firebase.database();
auth = firebase.auth();
var authProvider = new firebase.auth.GoogleAuthProvider(); //구글 인증창 선언
auth.onAuthStateChanged(function(user){
if (user) { //인증 성공 → need for login?
userInfo = user;
Attendances_dailyRef = database.ref('Attendances_daily/'+userInfo.uid );
document.GetValue.Database.value = JSON.stringify(Attendances_dailyRef);
} else {
auth.signInWithPopup(authProvider);
}
})
(html)
<form action="TimeSheet.php" name="GetValue" method="post">
<input type=submit style='font-size:16pt' value="シフト画面に行こう"/>
<input type=textarea name="Database" style='font-size:16pt'/>
</form>
TimeSheet.php
(php)
<?php
$AuthUser = json_decode($_POST["Database"]); //Ref
print_r($AuthUser);
?>
(javascript)
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"> </script>
<script>
function DBmodify() {
var buttonText = document.getElementById("modify").value;
if(buttonText == "修正終了") {
var Ref='<?=$AuthUser?>';
console.log(Ref);
Ref.on('value', function(data){
alert(data.val());
});
}
}
but it doesn't work. because of Ref type.
I send it JSON type, but it sended just text type(http address)
I want to know how can i send firebase database reference in web to other page.
is there any way?
(of course I know way
-> other firebase init in other page, but I want to use just one object)
==== edit ====
unfortunately my server native is php5.6 so I CAN'T USE FIREBASE PHP SDK
What I want to make
A system in which users send messages to administrators.
Progress
get uid (success)
get user info (fail)
If the user leaves a message, the administrator wants to see a list of them.
In the database,
messages {
uid1 {
key1 {
name : "user name"
text : "text that user remained"
created_at : "time that message created"
}
key2 {
…
}
…
}
uid2 {
…
}
}
I store the information as above. now be able to view this information as a list on the admin page..(and admin click on the list to see the message.)
However, I have succeeded in loading each uid, but I do not know how to use `uid 'to fetch the user's information.
Here is the output(now):
<div>uid1</div>
<div>uid2</div>
Here is the code:
function getListItem() {
var messagesRef = database.ref('personalchats') //personalchats 에 있는 uid로 접근
messagesRef.on('child_added', setListItem);
messagesRef.on('child_changed', setListItem);
}
function setListItem(data) {
var key = data.key;
var html = '<div class="listitem"> ' + key + '</div>;
$(".collection").append(html);
}
I want this result to be:
<div>userName1 : current message</div>
<div>userName2 : current message</div>
...
What can I do for it?
Thank you.
convert the data using data() and then extract it using the value names given in the database.
function getListItem() {
var messagesRef = database.ref('personalchats') //personalchats
messagesRef.on('child_added', setListItem);
messagesRef.on('child_changed', setListItem);
}
function setListItem(data) {
var key = data.key;
// create a variable to store the data
var dataVal=data.val();
var msgtext=dataVal.text;
var html = '<div class="listitem"> ' + key + ': '+ msgtext</div>;
$(".collection").append(html);
}
I have a problem, I used a get and post function to retrieve and save some url in my database, but now I d like to update a variable count, that should rapresent the votes that every video get, and after that I shoul be able to disable the button that a user click to vote. So I'm having some troubles to make the update function, or I should use another post? But if so I probably create another element inside my DB or not?
so here there is my video and for now I set the video's id invisible using css, to test it and try to find the video with that specific id and make the update
<p class="invisible" id="idVideo"> {{item._id}} </p>
<iframe class="partecipant" v-bind:src="item.video.url"> </iframe>
<p id="voti" > {{item.voti.count}} </p>
<input type="button" id="buttonVoti" v-on:click="addVoto">
so here, when the user click the button with id= buttonVoti the v-on click call addVoto function
methods: {
...
//ALL THE OTHERS METHODS
...
...
...
//AND THEN THE ADDVOTO FUNCTION
addVoto : function () {
var self = this;
//self.videos[1].voti.count++
//console.log(self.videos._id);
var i = document.getElementById("idVideo");
var idVid =i.innerHTML;
console.log(idVid);
so here I can change the variable count, using self....count++ but I have to store and then retrieve again the same video with the new count updated.
here there is my model so the logic to access to the count should be this one
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var videoSchema = new Schema({
video : {
id : String,
url : String,
idchallenge : String
},
voti : {
count : {}
}
});
module.exports = mongoose.model('Video', videoSchema);
yes so I have a method called load video, that is activated when the user click a button called loadVideo
loadVideo : function (){
var linkYoutube = this.text;
console.log(linkYoutube);
//POST
axios.post('/video',{
method: 'post',
video: {
id: '1',
url: linkYoutube
},
voti: {
count: 0
}
});
and this is my get function,
getVideo: function () {
var self = this;
// Make a request for a user with a given ID
axios.get('/video')
.then(function (response) {
self.videos = response.data;
console.log(self.videos);
When you do you GET request to your video route, in your route logic, you should be able to use Mongoose count. Here is what that route might look like:
var Router = require('express').Router();
var mongoose = require('mongoose');
var Video = mongoose.model('Video');
Router.get('/videos', function(req, res) {
var response = {};
Video.find({}, function(queryErr, videos) {
if (!queryErr) {
response.videos = videos;
Video.count({}, function(countErr, count) {
if (!countErr) {
response.count = count;
res.status(200).send(response);
} else {
res.status(500).send(countErr);
}
});
} else {
res.status(500).send(queryErr);
}
});
});
module.exports = Router;
Here is a question about Mongoose count on Stack Overflow.
So I am new to web development and Firebase as well. I have been trying to build a multi page web app in simple javascript and firebase. App looks good and works for most of the part. Yet it is really of no use as I am having following issue :
When I sign in through googleAuthProvider (on my index.html page), I am taken to another page which is main.html . Now til here is fine. But once the main.html is loaded, it goes into a loop of continuous refreshing.
My rationale behind this is, that somehow Firebase is trying to re-authenticate the page on loading. And so the loop happens. But why, this I am not able to debug.
I have looked over almost everything I could find on internet but no where I could find a solution which is for simple javascript based multi page web app with firebase.
Here's a link to my app if anyone is interested and kind enough to have a look.
Chatbot
Also, here is my javascript code too.
var config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX"
};
firebase.initializeApp(config);
//===============================================================================================
$("document").ready(function(){
const signinGoogle = document.getElementById("googleAuth");
const signOut = document.getElementById("signout");
const sendMsg = document.getElementById("send");
const messageBox = document.getElementById("chatBox");
const displayNAME = document.getElementById("dipslayName");
const storageRef = firebase.storage().ref();
var currentUser;
var name;
var photoUrl;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initApp();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signinGoogle){
googleAuth.addEventListener('click', e=>{
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var tokenGoogle = result.credential.accessToken;
// The signed-in user info.
var userGoogle = result.user;
// ...Below line to be rmeooved if not working expectedly.
// var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signOut){
signout.addEventListener('click', e=>{
if(confirm("Do you wish to leave?")){
promise = firebase.auth().signOut().then(function(){
window.location = "index.html";
});
promise.catch(e =>
console.log(e.message))
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initApp(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
$("document").ready(function(){
currentUser = firebase.auth().currentUser;
name = currentUser.displayName;
photoUrl = currentUser.photoURL ;
console.log("Current user's name is : "+name);
console.log("Current user's photoUrl is : "+photoUrl);
displayNAME.innerHTML = "Hi "+name;
//+++++++++++Retrieving Msgs++++++++++++++++++++++++++++++++
var i=1;
var firebaseRetrieveRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseRetrieveRef.on("child_added", snap =>{
var retrievedMsg = snap.val();
console.log("retrieved msgs is : "+retrievedMsg);
$("#taskList").append("<li id='list"+i+"'><div style='width:100%'><img src='"+photoUrl+"'style='width:10px;height:10px;border-radius:5px;'/><label>"+name+"</label></div><div style='width:100%'><p>"+retrievedMsg+"</p></div></li>");
i++;
});
//+++++++++++Storing Msgs++++++++++++++++++++++++++++++++
$("#send").on("click", function(){
var newMessage=messageBox.value;
if(newMessage==""){
alert("Empty Message doesn't make any sense, does it?? ");
}
else{
var firebaseStoreRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseStoreRef.push().set(newMessage);
messageBox.value="";
}
});
//+++++++++++Clearing/deleting all tasks++++++++++++++++++++++++
$("#clear").on("click", function(){
var firebaseDeleteRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseDeleteRef.remove();
$( ".scrolls" ).empty();
});
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
}
else
{
console.log(user+" is not logged in");
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
You keep redirecting to main.html.
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
You keep redirecting to main.html whenever you determine the user is signed in. Make sure on main.html, you are not using the same logic and redirecting again.