I have set up a site that takes some user data on a form and posts it to a server, it works when I manually put in the values and will send data to my firebase database
When I use UnityWebRequest's post, the download thing returns the code with the correct POST["xx"] values replaced but the javascript code seems to not have run
Unity Code C#:
WWWForm form = new WWWForm();
form.AddField("username", CreateUsernameInput.text);
form.AddField("email", EnterEmailInput.text);
form.AddField("password", CreatePasswordInput.text);
UnityWebRequest www = new UnityWebRequest();
using (www = UnityWebRequest.Post("https://smallgrains.000webhostapp.com/blobs&dices/create_player_data_slot.php, form))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
else
{
Debug.Log(www.downloadHandler.text);
}
}
Php Code:
<script type="module" src="https://www.gstatic.com/firebasejs/9.8.4/firebase-database.js"></script>
<p id = res></p>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp} from "https://www.gstatic.com/firebasejs/9.8.4/firebase-app.js";
import {getFirestore, collection, addDoc, setDoc, doc, getDoc} from 'https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js'
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app\'s Firebase configuration
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxx",
appId: "xxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
var iterations = 0
var username = '<?php echo $_POST["username"]; ?>';
var email = '<?php echo $_POST["email"]; ?>';
var password = '<?php echo $_POST["password"]; ?>';
var docRef = doc(db, "userdata", username + "_0");
var gotDoc = await getDoc(docRef);
while (gotDoc.exists())
{
iterations += 1
docRef = doc(db, "userdata", username + "_" + iterations);
gotDoc = await getDoc(docRef);
//console.log("Checking Next Document");
}
console.log('Yay, we found an empty slot after ' + iterations + ' checks!');
await setDoc(doc(db, "userdata", username + "_" + iterations), {
scores: [],
});
await setDoc(doc(db, "userdata", username + "_" + iterations, "private","login info"), {
username,
email,
password,
});
document.getElementById("res").innerHTML = username + "_" + iterations;
</script>
Related
i have this issue of 'firebase is not defined' when i try to read and display data from the relatime database.
I am using firebase to host a simple site in which you input 4 values and receive a score back, everything is scored in the database. i then want to display the highest 10 scores from the database, and im having trouble doing that.
Ive seen lot of people having this issue, but their resolutions are not working for me
Here is my code
function displayTopScores() {
// Reference to the scores in the database
var scoresRef = firebase.database().ref("scores");
// Retrieve the top 10 scores
scoresRef.orderByChild("Score").limitToFirst(10).on("value", function(snapshot) {
var scores = snapshot.val();
// Array to store the top 10 scores
var topScores = [];
// Add the scores to the array
for (var score in scores) {
topScores.push(scores[score]);
}
// Sort the scores in descending order
topScores.sort(function(a, b) {
return b.Score - a.Score;
});
// Create a table to display the scores
var table = document.createElement("table");
table.setAttribute("class", "table table-striped");
// Add a header row to the table
var headerRow = table.insertRow(-1);
var nameHeaderCell = headerRow.insertCell(-1);
nameHeaderCell.innerHTML = "Name";
var scoreHeaderCell = headerRow.insertCell(-1);
scoreHeaderCell.innerHTML = "Score";
// Add a row for each score
for (var i = 0; i < topScores.length; i++) {
var row = table.insertRow(-1);
var nameCell = row.insertCell(-1);
nameCell.innerHTML = topScores[i].Name;
var scoreCell = row.insertCell(-1);
scoreCell.innerHTML = topScores[i].Score;
}
// Add the table to the HTML page
var scoresContainer = document.querySelector("#scores-container");
scoresContainer.innerHTML = "";
scoresContainer.appendChild(table);
});
}
const dbRef = ref(getDatabase());
get(child(dbRef, `scores/Scores`)).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
i have imported (i think) all the right things for this to happen, but i am clearly doing some mistake i have not figured out.
here is what i import:
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "---",
authDomain: "---",
databaseURL: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const database = getDatabase();
I've read the documentation on how to import the database and app function, looked at other people with the same issue, tried to ask openAI but with no luck.
tried using different ways of creating a reference and read the data.
You need to pass the app variable as a parameter to getDatabase() it should be getDatabase(app)
Here is the official code from the firebase documentation:
import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";
const firebaseConfig = {
// ...
databaseURL: "https://DATABASE_NAME.firebaseio.com",
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
You can follow further examples from the documentation here: https://firebase.google.com/docs/database/web/start#web-version-9
function displayTopScores() {
const dbRef = ref(getDatabase());
get(child(dbRef, `scores/`)).then((snapshot) => {
if (snapshot.exists()) {
console.log(snapshot.val());
document.getElementById("scores-list").innerHTML = console.log(snapshot.val());
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
}
its not complete solution cause i still cant show in my site the values from the database, but this seems to fix the issue at least in part, now i see the database getting read from the chrome dev tool
I'm having a list of E-Mail subscribers and want to add a new one on button click. This should be possible for non-logged-in users. Therefore there need to be a check if this entry is already in the database. As I don't want to expose the full list to the non-logged-in user, how would I check if an E-Mail address already exists without making a fetch GET request that is having rights to access that list with firebase, as the whole code is exposed in the frontend? I'm working with version Web9.
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, getDocs, query, where } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { getAnalytics } from "firebase/analytics";
const firebaseConfig = {
apiKey: "",
authDomain: "",
projected: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth(app);
Fuction for adding the doc:
const addDocument = (dbName, obj) => {
return addDoc(collection(db, dbName), obj);
};
With the Firestore security rules you can break down a read rule into get and list as explained in the doc.
In your case you would assign read access to everybody with the get rule and deny access to the list rule. This way, the unauthenticated users can only fetch a specific document (identified with a specific email address) and verify if this given "entry" is already in the database. They cannot list all the existing entries.
Of course, a user could try many different email addresses but will not be able to directly get the list of all existing entries in the database with one query.
Here is my code solution that hopefully helps somebody. The goal has been to check if a single document exists and restrict the database access to check existence. I found only one possible option to do this (Excluding cloud functions). Thanks to #RenaudTarnec answer. There is no way to get a single doc with a query by field value. The only option is to set the id of the document to the specified E-Mail address (value you want to query).
Code:
Check if already subscribed, if not add to database of subscribers:
const [error, setError] = useState("");
const [message, setMessage] = useState("");
const handleSubmit = async (values: { email: string }) => {
const dbName = "newsletterSubscribers";
const docId = values.email;
setMessage("");
setError("");
const docRef = doc(db, dbName, docId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
// E-Mail address already subscribed, data: docSnap.data())
setMessage("E-Mail address already subscribed");
} else {
// E-Mail is not yet subscribed
try {
const docRef = await setDoc(doc(db, dbName, docId), {
createdAt: serverTimestamp(),
});
alert("Thank you for subscribing, you will receive all news and updates to " + values.email);
} catch (e) {
// Error adding document
setError("Failed to subscribe. We're sorry there was an error.");
}
}
};
Security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /newsletterSubscribers/{subscriberId} {
allow get: if true;
allow list: if false;
allow create: if true;
}
}}
I'm starting a small project with Vuejs and Firebase. I am trying to upload Name and Price to Firestore. I checked their documentation and few tutorials, but I am stuck with this error.
<div class="form-group">
<v-btn v-on:click="saveData" class="btn btn-primary">Save data</v-btn>
</div>
import db from "../firebase";
export default {
name: "products",
props: {
msg: String,
},
data() {
return {
aon: {
Name: null,
Price: null,
},
};
},
methods: {
saveData() {
db.collection("Products")
.add(this.Product)
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
},
},
};
Here is my firebase.js
import firebase from '#firebase/app';
import '#firebase/auth';
import '#firebase/firestore';
const fb = firebase.initializeApp({
apiKey: "!!!!!!!!!!!",
authDomain: "!!!!!!!!",
databaseURL: "!!!!!!!",
projectId: "!!!!!!",
storageBucket: "!!!!!!!",
messagingSenderId: "!!!!!!!",
appId: "!!!!!!!!!",
measurementId: "!!!!!!!!!!!!"
});
const db = firebase.firestore();
export default firebase;
export {db,fb} ;
First you didn't initialized your firebase app. To do so :
//firebase.js
const db = firebase.initializeApp(fb)
export {db.firestore(),fb}
Then on your products page or component you wrote :
//products.vue
db.collection("Products").add(this.Product)...
this.Product object doesn't exist so it should be this.aon
//products.vue
db.collection("Products").add(this.aon)...
For more info : https://firebase.google.com/docs/firestore/quickstart
As per the documentation here and here you need to use the .set(), .add(), .update() and .doc() methods like this.
When you use set() to create a document, you must specify an ID for the document to create. For example:
await db.collection('cities').doc('new-city-id').set(data);
to let Cloud Firestore auto-generate an ID for you. You can do this by calling add()
// Add a new document with a generated id.
const res = await db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
});
console.log('Added document with ID: ', res.id);
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc()
const newCityRef = db.collection('cities').doc();
// Later...
const res = await newCityRef.set({
// ...
});
To update some fields of a document without overwriting the entire document, use the update() method:
const cityRef = db.collection('cities').doc('DC');
// Set the 'capital' field of the city
const res = await cityRef.update({capital: true});
I have a contact form which contain attributes like first name, last name, phone number etc. That information stores in my database. my requirement is either after the information stored in database clicking submit in contact form or directly the information filled by user has to reach my mail. I need javascript for that. please help friends....I'm not good in javascript.
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyAR-fxVU8rhScgFN6V5hDFr8DKAZI7KM5k",
authDomain: "healthbharat-fa468.firebaseapp.com",
projectId: "healthbharat-fa468",
storageBucket: "healthbharat-fa468.appspot.com",
messagingSenderId: "1058506343655",
appId: "1:1058506343655:web:5915e61a8697670a818e42"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//referencing the collection
let contactInfo = firebase.database().ref("information");
//listen for submit
document.querySelector(".form_container2").addEventListener("submit",submitForm);
function submitForm(e) {
e.preventDefault();
//fetching the input values
let fname = document.querySelector(".fname").value;
let lname = document.querySelector(".lname").value;
let email = document.querySelector(".mail").value;
let number = document.querySelector(".phoneno").value;
let country = document.querySelector(".country").value;
let message = document.querySelector(".subject").value;
//console.log(fname, lname, email, number, country, message);
saveInformation(fname, lname, email, number, country, message);
document.querySelector(".form_container2").reset();
sendEmail(fname, lname, email, number, country, message);
}
//save the information to firebase
function saveInformation(fname, lname, email, number, country, message) {
let newinformation = contactInfo.push();
newinformation.set({
fname: fname,
lname: lname,
email: email,
number: number,
country: country,
message: message,
});
retrieveInformation();
}
//retrieve information
function retrieveInformation(){
let ref = firebase.database().ref("information");
ref.on("value", gotData);
}
function gotData(data) {
let infor = data.val();
let keys = Object.keys(infor);
for(let i = 0;i < keys.length; i++){
let infdata = keys[i];
let fname = infor[infdata].fname;
let lname = infor[infdata].lname;
let email = infor[infdata].email;
let number = infor[infdata].number;
let country = infor[infdata].country;
let message = infor[infdata].message;
console.log(fname, lname, email, number, country, message);
}
}
//Sending email
function sendEmail(fname, lname, email, number, country, message) {
Email.send({
Host: "smtp.gmail.com",
Username: 'Healthbharat',
Password: "Healthybharat",
To: 'avinash9490251214#gmail.com',
From: 'healthybharatinfo#gmail.com',
Subject: `${fname} has raised a complaint`,
Body: `Name🙂 ${fname} <br> Email📧 ${email} <br> Message📔 ${message}`,
}).then( message => alert("mail sent successfully"));
}
I'm using Firebase at a school project and I'm having the same problem a while... I have looked at various sites but I can't find anyone with the same problem...
The User authentication is working correctly, but the problem is with saving the user data in the database.
I have two available ways to authenticate:
Email and password;
Facebook.
With email and password, the data is written successfully in the database, and I'm using the following JavaScript code:
function signUp(){
//Get DOM data
const email = String(document.getElementById('TXTEmail').value);
const pass = String(document.getElementById('TXTPassword').value);
const name = String(document.getElementById('TXTNome').value);
const gender = document.registo.sexo.value;
const auth = firebase.auth();
var promise = auth.createUserWithEmailAndPassword(email,pass);
promise.catch(e => console.log(e.message));
firebase.database().ref('users/' + firebase.auth().currentUser.uid).set({
name : name,
email : email,
gender : gender,
uid: firebase.auth().currentUser.uid
});
}
However, when using the function of facebook I can't save the data, I can only authenticate the user, and the code I'm using is as follows:
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
}
// The signed-in user info.
var user = result.user;
const name = user.displayName;
const email = user.email;
const photo = user.photoURL;
if(user != 0) {
firebase.database().ref('users/' + user.uid).set({
name: nome,
email: email,
photo: photo,
uid: user.uid
});
}
//Tests only
if(user != 0){
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).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;
});
}
And I get this output on my console:
Console output.
name: Rafael Veloso
email: rafael****#gmail.com
photoUrl: scontent.xx.fbcdn.net/v/t1.0-1/s100x100/…
uid: **HY43Tl******KoO6OhZjG****
Also, my database.rules.json is:
{
"rules": {
".read": true,
".write": true
}
}
Does anyone know what is the problem that I'm having?
Thank you.
with the help of the Firebase support I managed to solve my problem :)
First, created a script within the .html document like that:
<script>
document.getElementById('btnFacebook').addEventListener('click', signUpFacebook, false);
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
}
function createNewPost(name, email, photo, uid) {
firebase.database().ref('users/' + uid).set({
name: name,
email: email,
photo: photo,
uid: uid
});
}
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
var token = result.credential.accessToken;
}
// The signed-in user info.
if(user != null) {
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).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;
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var name = user.displayName;
var email = user.email;
var photo = user.photoURL;
var uid = user.uid;
createNewPost(name, email, photo, uid);
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
});
With just that, I still wasn't able to add the user data to the Realtime Database, so I changed my "imports", I was with this:
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
and only when I changed to the following I was able to save the user data in the Database:
<!-- <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
But I find that strange, can anyone help and explain me why that worked out?