I've set up a firebase realtime database, and when I run my code, it works in safari but it doesn't work in chrome.
This is my index.js file link to an html file as <script type="module" src="index.js"></script>
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js';
import { getDatabase, set, ref } from 'https://www.gstatic.com/firebasejs/9.1.2/firebase-database.js';
const firebaseApp = initializeApp({
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
});
const db = getDatabase(firebaseApp)
var x = document.getElementById("Identifiant");
var y = document.getElementById("Password");
function senddata(){
set(ref(db, 'users/' + x.value), {
username: x.value,
password: y.value
});
window.location.href = 'https://www.youtube.com';
};
var btn = document.getElementById('btnconx');
btn.addEventListener('click', senddata);
So this works in safari, but in chrome, it does send me to YouTube but it doesn't write in the database. But if I don't put the "window.location.href = 'https://www.youtube.com';", it will send the data to the database even in chrome. How do I make it work so that after it writes the data to the database, it sends the user to YouTube (or basically any website). Note that the button "btn" as the type="button" and is inside a form with the method="GET".
It sounds like it may be redirecting your page before it gets a chance to send your data. To remedy this I'd suggest making senddata() asynchronous and awaiting set(). This should allow your page to send the data before redirecting.
ES6
async function senddata(){
await set(ref(db, 'users/' + x.value), {
username: x.value,
password: y.value
});
window.location.href = 'https://www.youtube.com';
};
ES5
function senddata(){
set(ref(db, 'users/' + x.value), {
username: x.value,
password: y.value
}).then(() => {
window.location.href = 'https://www.youtube.com';
});
};