Search code examples
javascriptwebfirebase-realtime-databasehrefsession-storage

Cannot redirect to another html file after saving data to firebase in my web


I want to add some session storage values to the database and then redirect the page to another html file. But when i insert the redirecting code, the data are not getting saved to firebase but when i comment the code to redirect the page, the data are getting stored in firebase just as expected. How do i redirect to another html file after these data are stored in firebase?

function bookingConfirm(){

var id = 4;
var firebaseRootRef = firebase.database().ref().child("Orders");
var firebaseIdRef = firebaseRootRef.child(id);

firebaseIdRef.child("id").set(id);
firebaseIdRef.child("user").set(sessionStorage.getItem("userName"));
firebaseIdRef.child("movie").set(sessionStorage.getItem("movie"));
firebaseIdRef.child("date").set(sessionStorage.getItem("date"));
firebaseIdRef.child("seats").set(sessionStorage.getItem("seats"));
firebaseIdRef.child("snacks").set(sessionStorage.getItem("snacks"));
firebaseIdRef.child("ticket price").set(sessionStorage.getItem("total"));
firebaseIdRef.child("snack price").set(sessionStorage.getItem("snackPrice"));
firebaseIdRef.child("total price").set(sessionStorage.getItem("finalPrice"));

alert(" Your booking is done! ");
// location.href = "main.html";
// document.getElementById("quithref").setAttribute("href","main.html");

}


Solution

  • Add a completion callback, like so:

    firebaseIdRef.child("total price").set("I'm writing data", function(error) {
      if (error) {
        alert("Data could not be saved." + error);
      } else {
        alert("Data saved successfully.");
      }
    });
    

    From the docs: https://firebase.google.com/docs/database/admin/save-data#section-completion-callback