Unable to write data to Firebase realtime database, rules checked - firebase

I have problem with writting data to realtime database. I don't know why I can't write anything to database, I checked the database rules and it's allowed to write data
`
var firebaseConfig = {
//key
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Database reference
var firebaseRef = firebase.database().ref();
// The click Event
document.getElementById('send').addEventListener('click', function(){
firebaseRef.push(document.getElementById('email').value);
});
<html lang="en">
<head>
<title>Firebase</title>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
</head>
<body>
E-mail:<input type="email" id="email">
<button id="send"> Send </button>
<script src="main.js"></script>
</body>
</html>
`

Related

How to manually add a document to a collection in Firestore database?

I have a quite simple database in Firestore (geographic name, lat and Lon). The database is very static and I only need to add or remove a record (document) once a while.
How can I add a record manually to the collection, with the same fields as the other documents? When I press "Add document" the console asks me to input each field (see screenshot).
The following HTML page will allow you to write to your spots Firestore collection.
You need to adapt the fields, of course, as well as the Firebase config.
If you want to authenticate, just add two extra fields e.g. Username and Password and use the signInWithEmailAndPassword() method. (I can adapt the page if you want).
You can host this page in Firebase hosting for example, taking advantage of the SSL Certificate. Or you can simply save it on your computer and open it with a browser (not HTTPS in this case, but a good way to test).
<!DOCTYPE html>
<html>
<head>
<title>Firebase Form</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-auth.js"></script>
</head>
<body>
<div>
<p>Name:</p>
<input type="text" placeholder="Name" id="name" />
<p>City:</p>
<input type="text" placeholder="City" id="city" />
<br /><br />
<input type="submit" value="submit" class="submit" id="submit" />
</div>
<script>
$(document).ready(function() {
// Initialize Firebase
var config = {
apiKey: 'xxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxxx',
databaseURL: 'xxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxx'
};
firebase.initializeApp(config);
var database = firebase.firestore();
$('#submit').on('click', function() {
var nameValue = $('#name').val();
var cityValue = $('#city').val();
var dataObject = {
name: nameValue,
city: cityValue
};
database.collection('spots').add(dataObject);
});
});
</script>
</body>
</html>
You can't, you'll have to write or use a tool to do this.

Firebase - run "functions.https" in a cloud function when button clicked

Is it possible to get a firebase cloud function to run from clicking a button in HTML?
html
<html>
<head>
<title>My Title</title>
</head>
<body>
This is some content
<button onclick="exports.testName('testTxt')">click test</button>
</body>
</html>
index.js
const functions = require('firebase-functions');
exports.testName = functions.https.onRequest((req, res) => {
res.status(200).send(`New Content`);
});
Yes it's call callable function look at this: https://firebase.google.com/docs/functions/callable

Phonegap CRUD operations - window.openDatabase

Am trying to create a CRUD operation using phonegap/cordova, and I keep receiving "Uncaught DOMException: An attempt was made to break through the security policy of the user agent. at window.onload - Line 17" pointing to =>"db = window.openDatabase("employee", "1.1", "LearnToProgram", 200000);". This further affects db.transaction Line 25 “Uncaught TypeError: Cannot read property 'transaction' of undefined”, because Database was not created. Do I need any SQLLite plugin on maybe there is something else missing?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>SQLLite DB App</title>
<script type="text/javascript" src="cordova.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script>
var db;
window.onload=function()
{
document.getElementById('btnSave').addEventListener('click', saveData);
db = window.openDatabase("employees", "1.0", "LearnToProgram", 200000);
}
function saveData(e)
{
db.transaction(saveRecord, onSuccess, onError);
}
function saveRecord(transaction)
{
var name= document.getElementById('name').value;
var email = document.getElementById('email').value;
transaction.executeSql('CREATE TABLE IF NOT EXISTS employeesList (id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT NOT NULL, Email TEXT NOT NULL) ');
var sql= "INSERT INTO employeesList (Name,Email) VALUES ('" + name +"', '" + email + "')";
console.log(sql);
transaction.executeSql(sql);
}
function onSuccess()
{
console.log("Record Saved");
}
function onError(error)
{
console.log("SQL error: " + error.code);
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header"><h1>Database Storage</h1></div>
<div data-role="main" class="ui-content">
<label for="name">Name</label>
<input type="text" id="name" />
<label for="email">Email</label>
<input type="text" id="email" />
<button id="btnSave" type="submit">Save</button>
<button id="showList">Show Employees</button>
</div><!-- main-->
</div><!-- page -->
</body>
</html>
maybe I help you.
To open a database:
var db = null;
document.addEventListener('deviceready', function() {
db = window.sqlitePlugin.openDatabase({
name: 'my.db',
location: 'default',
});
});
IMPORTANT: Like with the other Cordova/phonegap plugins your application must wait for the deviceready event. This is especially tricky in Angular/ngCordova/Ionic controller/factory/service callbacks which may be triggered before the deviceready event is fired.

AngularFire doesn't show data from Firebase Database

I'm following this video. But I have trouble implementing it. This is the HTML file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome to Firebase Hosting</title>
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.0.2/angularfire.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.3.0/firebase.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="app">
<div id="message" ng-controller="MyController as ctrl">
<pre>
{{ ctrl.object | json }}
</pre>
</div>
</body>
</html>
And my app.js file is this.
(function(){
// Initialize Firebase
var config = {
apiKey: "SOME KEY",
authDomain: "tier2list.firebaseapp.com",
databaseURL: "https://tier2list.firebaseio.com",
storageBucket: "",
};
firebase.initializeApp(config);
angular.module('app', ['firebase']).controller('MyController', function($firebaseObject){
const rootRef = firebase.database().ref().child('tier2list');
const ref = rootRef.child('object');
this.object = $firebaseObject(ref);
});
}());
This is my database structure.
But the result is as follows.
And there is no errors in the console as well. Database rules are as follows.
{
"rules": {
".read": true,
".write": true
}
}
The problem is in the path you synchronize:
const rootRef = firebase.database().ref().child('tier2list');
There is no child tier2list in your database, so you will get an empty object.
Instead, you're trying to synchronize the entire database, which you can do by:
const rootRef = firebase.database().ref()
I was in the middle of this when Frank answered. He has the right answer, but here is what your database should look like in order to work with David's code:
In his walk through, he is already inside of the angular node, so that could be a little confusing.
I also created a Github repo for the project in case anyone is having trouble making it for themselves:
https://github.com/LukeSchlangen/angularFireQuickDemo

"TypeError: undefined is not a function" when trying to push() to Firebase

Upon submission of a form, I want to push that data to my Firebase db and so I'm creating a function to do so (addMeeting). However, upon pressing the button to submit I get the error:
TypeError: undefined is not a function
at l.$scope.addMeeting (http://localhost:8000/js/controllers/meetings.js:10:12)
meetings.js:10:12 is right where my $push is if you'll look at my code below.
My HTML:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Angular Data</title>
<meta name="viewport" content="width=device-width, userscalable=no">
<link rel="stylesheet" href="css/style.css">
<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="js/lib/angular/angular-route.min.js"></script>
<script src="js/lib/angular/angular-animate.min.js"></script>
<!-- Firebase -->
<script src="https://cdn.firebase.com/js/client/2.2.2/firebase.js"></script>
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/1.0.0/angularfire.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/registration.js"></script>
<script src="js/controllers/meetings.js"></script>
</head>
<body>
<header>
<nav class="cf" ng-include="'views/nav.html'"></nav>
</header>
<div class="page">
<main class="cf" ng-view></main>
</div>
</body>
</html>
My apps.js:
var myApp = angular.module('myApp',
['ngRoute', 'firebase', 'appControllers']);
var appControllers = angular.module('appControllers', ['firebase']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
controller: 'RegistrationController',
templateUrl: 'views/login.html'
}).
when('/register', {
controller: 'RegistrationController',
templateUrl: 'views/register.html'
}).
when('/meetings', {
controller: 'MeetingsController',
templateUrl: 'views/meetings.html'
}).
otherwise({
redirectTo: '/login'
});
}])
meetings.js -the Controller containing the addMeeting function that is failing:
myApp.controller('MeetingsController',
function($scope, $firebaseObject) {
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseObject(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
}); //MeetingsController
The view that is calling that function upon submission of a form:
<section class="meetings cf">
<h1>Add Meetings</h1>
<form class="formgroup addmeeting cf"
name="myform"
ng-submit="addMeeting()"
novalidate>
<div class="inputwrapper">
<input type="text" name="meetingname" placeholder="Meeting Name"
ng-model="meetingname" ng-required="true">
</div>
<button type="submit" class="btn"
ng-disabled="myform.$invalid">+</button>
</form>
<h2>Your Meetings</h2>
<div class="meeting" ng-repeat="meeting in meetings">
<p>{{meeting.name}}</p>
</div>
</section>
**Edit: ** It has something to do with the .push() method itself. I see that in the latest version of angularfire/firebase it should be .push, instead of .$push, ad have changed that but it does not solve my problem. I reverted AngularFire and Firebase to versions 0.8.2 and 1.0.21 respectively, re-introduced the .asObject() and $push, and everything works fine. I don't understand why .push() is failing with all the latest (Firebase 2.2.2, AngularFire 1.0).
Firebase's AngularFire library has two primary types: $firebaseObject and $firebaseArray (instantiated through $asObject and $asArray respectively in pre-1.0 versions of AngularFire).
You're using both the wrong type and the wrong method. To quote AngularFire's documentation on its array type:
Synchronized arrays should be used for any list of objects that will be sorted, iterated, and which have unique IDs. The synchronized array assumes that items are added using $add(), and that they will therefore be keyed using Firebase push IDs.
So:
var ref = new Firebase('https://angulardataldc.firebaseio.com/meetings');
var meetings = $firebaseArray(ref);
$scope.meetings = meetings;
$scope.addMeeting = function() {
meetings.$add({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
You made a typo, it should be .push instead of $push
CODE
$scope.addMeeting = function() {
meetings.push({
name: $scope.meetingname,
date: Firebase.ServerValue.TIMESTAMP
})
}
Reference

Resources