firebase.database is not a function error - html page - html

I've been trying to figure out how to connect firebase to a HTML page, but I keep getting an error saying firebase.database isn't a function.
I have already looked a lot of solutions for this, but most of them aren't applicable.
I have already tried changing <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script> to <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase.js"></script>
I have also tried importing firebase with import commands instead of using src links as per this solution: https://github.com/firebase/firebase-js-sdk/issues/1265, but it failed to find the packages.
Heres the applicable code:
<div>
<h1>Firebase web app</h1>
<button id="submitBtn" onclick="submitClick()">click here</button>
</div>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-storage.js"></script>
<script>
//Stats hidden for privacy, but I got this from a copy paste from my firebase SDK config snippet
const firebaseConfig = {
apiKey: (key),
authDomain: (domain),
databaseURL: (URL),
projectId: (id),
storageBucket: (storageBucket),
messagingSenderId: (senderId),
appId: (appId)
};
firebase.initializeApp(firebaseConfig);
function submitClick() {
var firebaseRef = firebase.database().ref();
firebaseRef.child("Text").set("some Value");
}
</script>

You're not importing the firebase-database.js SDK, which is what defines firebase.database().
To fix it, add:
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-database.js"></script>
In general: you should include only the SDKs you actually use. So with your current code, that'd just be firebase-app and firebase-database.

Related

Fixing TypeError for Firebase Google Sign In Authentication

I'm trying to create a simple Google SignIn button and when you press it, you are able to sign in with your google account. I am doing this using Google Firebase Authentication and I have enabled Google Sign-In (and Email/Password). However, I have run into multiple errors and I'm not sure what I'm doing wrong.
This is my code:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>GoogleSignUp</title>
</head>
<body>
<button onclick="googleSignIn()">Google SignIn</button>
<script
src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script>
var firebaseConfig = {
apiKey: "--------------",
authDomain: "--------------",
projectId: "productify-36d63",
storageBucket: "--------------",
messagingSenderId: "--------------",
appId: "--------------,
measurementId: "--------------"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
googleSignIn=()=>{
base_provider = new firebase.auth.GoogleAuthProvider()
firebase.auth().signInWithPopup(base_provider).then(function(result){
console.log(result)
console.log("Success... Google Account Linked")
}).catch(function(err){
console.log(err)
console.log("Failed")
})
}
</script>
</body>
</html>
I have no Errors until I actually click the button.
These are the errors that I get once I click the Sign-In Button:
I have looked everywhere, watched so many videos, read as much as I could from stackoverflow and have been trying to figure out how to create a google sign-in button using Firebase Authentication but nothings working.
Any help would be much appreciated. Thank you in advance!
You are missing the app and auth script
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js"></script>
You can find out more in the docs here

Jquery script working when inside the html file but fails when imported from an external file

I was following the documentation on socket.io website when I found this problem.
My working code
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function() {
$(function () {
var socket = io();
$('form').submit(function(e) {
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
})
</script>
When the same jquery script is imported from an external file, it fails.
client.js contains the exact same jquery script and in the same directory.
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="client.js"></script>
Below was the error from console, I'm not able to figure out what it is
The resource from “http://localhost:3000/client.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
Change your type to "application/javascript" for that script. Also, if you find that the script isn't loading, add the defer property to the script tag like below.
<script type="application/javascript" defer src="./client.js"></script>
Lastly, I've seen similar issues where the js isn't located at the source you're referencing. Please make sure your source link is correct.

Update values to firebase

Values are not getting updated in the Firebase Realtime Database. I am new to web development but I knew a little html. Can you please check what the problem here.
I left Firebase Config blank intentionally for this question.
I tried using most of the code given in Firebase documentation.
<!DOCTYPE html>
<html>
<head>
<title>"Web App"</title>
</head>
<body>
<div class="mainDiv" align="left">
<h1 align="left">"Firebase web page"</h1>
<textarea id="Command" placeholder="ON/OFF" stClyle="text align:left; overflow:auto; border:6px outset #000000;"></textarea>
<button id="Submit" onclick="submitclick()">Click Me!</button>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "___________________________",
authDomain: "_________.firebaseapp.com",
databaseURL: "https://___________.firebaseio.com",
projectId: "________",
storageBucket: "_________.appspot.com",
messagingSenderId: "________",
appId: "_____________"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var mainTxt= document.getElementById("Command");
var submitbtn = document.getElementById("Submit");
function submitclick()
{
var com = mainTxt.value;
firebase.database().ref().child("username").set(com);
}
</script>
</body>
</html>
Have a look at the documentation on how to add Firebase to your Web/JavaScript project: https://firebase.google.com/docs/web/setup
By doing
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js"></script>
you are adding the Firebase core library, but this is not sufficient. You have to add the library(ies) for the service(s) you are going to use, in your case the Realtime Database.
Therefore you need to do
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-database.js"></script>
Note the following line
<!-- TODO: Add SDKs for Firebase products that you want to use
in your own code: it indicates exactly what is described above.
First of all to use firebase you have to include
<script src="https://www.gstatic.com/firebasejs/6.1.0/firebase-firestore.js"></script>
Still it won't work because this is not how you write to firebase. You write as key value pairs. Try
firebase.database().collection("userNames").add({name : "user_name"});
or if you trying to update a document
firebase.database().ref().child("userName").set({name : "user_name"});
Here is the official documentation : Add and Manage Data
As on the topic calling .set() or .add() may not always write data you have to check by using then() and catch().
So a complete example of updating a document value in firebase will be :
// Add a new document in collection "cities"
db.collection("users").doc("userName").set({
name: "USER_NAME"
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});

Firebase authentication failing with auth/network-request-failed A network error (such as timeout

I have experienced very strange behaviour trying to do Firebase authnetication. Even more, I made a version that works and one that does not.
First, the version that works:
<!doctype html>
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDapkNCu9UwitvO84PwQHnUQ6e4g6UK7JM",
authDomain: "********.firebaseapp.com",
databaseURL: "https://*******.firebaseio.com",
projectId: "********",
storageBucket: "********.appspot.com",
messagingSenderId: "582605565305"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<script>
firebase.auth().signInWithEmailAndPassword("myemail#abc.xyz", "mypassword").catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorCode + " " + errorMessage);
// ...
});
</script>
</body>
</html>
And now the version that does not work and gives me the error stated in the title of this question.
<!doctype html>
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDapkNCu9UwitvO84PwQHnUQ6e4g6UK7JM",
authDomain: "**********.firebaseapp.com",
databaseURL: "https://*********.firebaseio.com",
projectId: "**********",
storageBucket: "**********.appspot.com",
messagingSenderId: "582605565305"
};
firebase.initializeApp(config);
</script>
<script src="myfirebase.js"></script>
</head>
<body>
<form name="myform">
<span class="prm">Email</span><input type="text" name="email"></br>
<span class="prm">Password</span><input type="password" name="password" ></br>
<input type="image" src="some.png" onClick="loginToFirebase();">
</form>
</body>
</html>
And myfirebase.js
function loginToFirebase(){
var myform = document.forms.myform;
if(myform){
alert("trying to log as:" + myform.email.value + " and:" + myform.password.value);
firebase.auth().signInWithEmailAndPassword(myform.email.value, myform.password.value).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorCode + " " + errorMessage);
// ...
});
}
}
As you can see it is very simple example and both versions are pretty much the same. The only difference is that in working version email and password are hardcoded into the source, but in nonworking version there is a HTML form and a small javascript.
I put alert statement to be sure that everything works as expected.
Here comes the strangest thing. Both version works in Firefox, but not in Chrome, Opera and Konqueror(I work on Linux/Fedora24). The same auth/network-request-failed A network error (such as timeout, interrupted connection or unreachable host) has occurred.
is shown.
Firebase console shows that the working version really works.
I cleared Chrome cache, with no result.
Can anyne help me?
Resolved!
I realized it has something with Content Security Policy, tried various options, and here is the solution.
First, instead of inline
onClick="loginToFirebase();"
I had to register event listener
function initApp(){
document.getElementById('mybutton')
.addEventListener('click', loginToFirebase);
}
window.onload = function() {
initApp();
}
This was not the end of my problems, tried to specify Content Security Policy, but with no result.
After very thoroughly looking at Firebase demo code, I decided to remove <form> tag and that was it!
Hope, it will help someone :)

Typeahead twitter bootstrap not functioning mvc4

I am trying to implement this code here
but I get no results while running the project.
here is my code:
View:
<input type="text" name="names" value="" id="typeahead" data-provide="typeahead" autocomplete="off" />
Again on view (index.cshtml):
<script type="text/javascript">
$(function () {
$('#typeahead').typeahead({
source: function (term, process) {
var url = '#Url.Content("~/index/GetNames")';
return $.getJSON(url, { term: term }, function (data) {
return process(data);
});
}
});
})
</script>
Controller (indexController.cs):
[HttpGet]
public JsonResult GetNames(string term)
{
// A list of names to mimic results from a database
List<string> nameList = new List<string>
{
"Jonathan", "Lisa", "Jordan", "Tyler", "Susan", "Brandon", "Clayton", "Elizabeth", "Jennifer", "Hadi"
};
var results = nameList.Where(n =>
n.StartsWith(term, StringComparison.OrdinalIgnoreCase));
return new JsonResult()
{
Data = results.ToArray(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
here are also the js scripts added at the end of the view page:
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery-1.9.1.intellisense.js"></script>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
here is also the list of bugs I get on runtime:
Uncaught TypeError: undefined is not a function bootstrap.js:29
Uncaught ReferenceError: intellisense is not defined jquery-1.9.1.intellisense.js:1
Uncaught TypeError: Object [object Object] has no method 'typeahead'
Please let me know what am i doing wrong!
This may be a bit old but you cannot use source: you must use either remote:, prefetch:, or local: as the error reads.
Which version of bootstrap are you using? The standalone plug-in no longer supports all of the different data providers in the same way as the old one did
First off, make sure you place the script tag referencing jquery first, before bootstrap. Also only load a single jquery script tag.
Like this:
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
All the JS libraries you are using at the moment have one dependancy: jQuery so they need to be loaded in right order:
<!-- jQuery should always be the first -->
<!-- jquery-1.9.1.js and jquery-1.9.1.min.js are the same but .min version is minified and always lighter, so use it for faster page load -->
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<!-- Any other library should be loaded after jQuery -->
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery-1.9.1.intellisense.js"></script>
Hope this helps ;)