Как отправить данные из формы регистрации Пользователя в базу данных firebase

заранее спасибо и извините, если этот вопрос задается ранее. Я новичок в firebase и javascript, здесь я создаю форму регистрации для пользователя со следующими полями:

  1. Username
  2. Company name
  3. Contact No
  4. Email address
  5. Password

Я тоже прошел через некоторые из учебников и образцов, но в этих учебниках я обнаружил, что есть только поля электронной почты и пароля который использовался при аутентификации, но в моем случае я хочу зарегистрировать пользователя, а также вставить имя пользователя, адрес электронной почты, название компании, Контакт нет в базе данных firebase...

может кто-нибудь, пожалуйста, помогите мне...ниже приведен мой код

<!DOCTYPE html>
<html>

<head>

  <!--Bootstrap CSS CDN-->
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <!---jQuery CDN-->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>






  <script type="text/javascript">
    /**
     * Handles the sign in button press.
     */
    function toggleSignIn() {
      if (firebase.auth().currentUser) {
        // [START signout]
        firebase.auth().signOut();
        // [END signout]
      } else {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;
        if (email.length < 4) {
          alert('Please enter an email address.');
          return;
        }
        if (password.length < 4) {
          alert('Please enter a password.');
          return;
        }
        // Sign in with email and pass.
        // [START authwithemail]
        firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // [START_EXCLUDE]
          if (errorCode === 'auth/wrong-password') {
            alert('Wrong password.');
          } else {
            alert(errorMessage);
          }
          console.log(error);
          document.getElementById('quickstart-sign-in').disabled = false;
          // [END_EXCLUDE]
        });
        // [END authwithemail]
        window.location = '/1home.php'
      }
      document.getElementById('quickstart-sign-in').disabled = true;
    }
    /**
     * Handles the sign up button press.
     */
    function handleSignUp() {
      var email = document.getElementById('email').value;
      var password = document.getElementById('password').value;
      if (email.length < 4) {
        alert('Please enter an email address.');
        return;
      }
      if (password.length < 4) {
        alert('Please enter a password.');
        return;
      }
      // Sign in with email and pass.
      // [START createwithemail]
      firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
        firebase.database().ref('users/' + user.uid).set({
          email: email,
          password: password
        })
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // [START_EXCLUDE]
        if (errorCode == 'auth/weak-password') {
          alert('The password is too weak.');
        } else {
          alert(errorMessage);
        }
        console.log(error);
        // [END_EXCLUDE]
      });
      // [END createwithemail]
    }


    /**
     * Sends an email verification to the user.
     */
    function sendEmailVerification() {
      // [START sendemailverification]
      firebase.auth().currentUser.sendEmailVerification().then(function() {
        // Email Verification sent!
        // [START_EXCLUDE]
        alert('Email Verification Sent!');
        // [END_EXCLUDE]
      });
      // [END sendemailverification]
    }

    function sendPasswordReset() {
      var email = document.getElementById('email').value;
      // [START sendpasswordemail]
      firebase.auth().sendPasswordResetEmail(email).then(function() {
        // Password Reset Email Sent!
        // [START_EXCLUDE]
        alert('Password Reset Email Sent!');
        // [END_EXCLUDE]
      }).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // [START_EXCLUDE]
        if (errorCode == 'auth/invalid-email') {
          alert(errorMessage);
        } else if (errorCode == 'auth/user-not-found') {
          alert(errorMessage);
        }
        console.log(error);
        // [END_EXCLUDE]
      });
      // [END sendpasswordemail];
    }
    /**
     * Handles registering callbacks for the auth status.
     *
     * This method registers a listener with firebase.auth().onAuthStateChanged. This listener is called when
     * the user is signed in or out, and that is where we update the UI.
     *
     * When signed in, we also authenticate to the Firebase Realtime Database.
     */
    function initApp() {
      // Listening for auth state changes.
      // [START authstatelistener]
      firebase.auth().onAuthStateChanged(function(user) {
        // [START_EXCLUDE silent]
        document.getElementById('quickstart-verify-email').disabled = true;
        // [END_EXCLUDE]
        if (user) {
          // User is signed in.
          var displayName = user.displayName;
          var email = user.email;
          var emailVerified = user.emailVerified;
          var photoURL = user.photoURL;
          var isAnonymous = user.isAnonymous;
          var uid = user.uid;
          var refreshToken = user.refreshToken;
          var providerData = user.providerData;
          // [START_EXCLUDE silent]
          document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';
          document.getElementById('quickstart-sign-in').textContent = 'Sign out';
          document.getElementById('quickstart-account-details').textContent = JSON.stringify({
            displayName: displayName,
            email: email,
            emailVerified: emailVerified,
            photoURL: photoURL,
            isAnonymous: isAnonymous,
            uid: uid,
            refreshToken: refreshToken,
            providerData: providerData
          }, null, '  ');
          if (!emailVerified) {
            document.getElementById('quickstart-verify-email').disabled = false;
          }
          // [END_EXCLUDE]
        } else {
          // User is signed out.
          // [START_EXCLUDE silent]
          document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';
          document.getElementById('quickstart-sign-in').textContent = 'Sign in';
          document.getElementById('quickstart-account-details').textContent = 'null';
          // [END_EXCLUDE]
        }
        // [START_EXCLUDE silent]
        document.getElementById('quickstart-sign-in').disabled = false;
        // [END_EXCLUDE]
      });
      // [END authstatelistener]
      document.getElementById('quickstart-sign-in').addEventListener('click', toggleSignIn, false);
      document.getElementById('quickstart-sign-up').addEventListener('click', handleSignUp, false);
      document.getElementById('quickstart-verify-email').addEventListener('click', sendEmailVerification, false);
      document.getElementById('quickstart-password-reset').addEventListener('click', sendPasswordReset, false);
    }
    window.onload = function() {
      initApp();
    };
  </script>
</head>

<body>
  <div class="jumbotron text-center">

  </div>

  <div class="container">
    <div class="jumbotron">

      <div class="row">
        <div class="col-md-6">
          <!--<img src="" style="width:500px; height:340px">-->

        </div>

        <div class="col-md-6">

          <!-- Container for the demo -->
          <div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop">
            <div class="mdl-card__title mdl-color--light-blue-600 mdl-color-text--white">
              <h2 class="mdl-card__title-text">Sign Up</h2>
            </div>

            <div class="mdl-card__supporting-text mdl-color-text--grey-600">
              <p>Enter an email and password below and either sign in to an existing account or sign up</p>
              <input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="text" name="text" placeholder="companyname" /> &nbsp;&nbsp;&nbsp;
              <br /><br />
 <input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="text" name="text" placeholder="name" /> &nbsp;&nbsp;&nbsp;
              <br /><br />


              <input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="email" name="email" placeholder="Email" /> &nbsp;&nbsp;&nbsp;
              <br /><br />
              <input class="mdl-textfield__input" style="display:inline;width:auto;" type="password" id="password" name="password" placeholder="Password" />
              <br/><br/>
              <button disabled class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-in" name="signin">Sign In</button> &nbsp;&nbsp;&nbsp;
              <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-up" name="signup">Sign Up</button> &nbsp;&nbsp;&nbsp;
              <button class="mdl-button mdl-js-button mdl-button--raised" disabled id="quickstart-verify-email" name="verify-email">Send Email Verification</button> &nbsp;&nbsp;&nbsp;
              <button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-password-reset" name="verify-email">Send Password Reset Email</button>

              <!-- Container where we'll display the user details -->
              <div class="quickstart-user-details-container">
                <!--Firebase-->sign-in status: <span id="quickstart-sign-in-status">Unknown</span>
                <div>
                  <!--Firebase-->auth <code>currentUser</code> object value:</div>
                <pre><code id="quickstart-account-details">null</code></pre>
              </div>
            </div>
            <!---->
          </div>

        </div>
      </div>

    </div>



    <!--Bootstrap Js CDN-->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <!--Firebase Initialization-->
    <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
    <script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/1.2.0/angularfire.min.js"></script>

    <script>
      // Initialize Firebase
      var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        messagingSenderId: ""
      };
      firebase.initializeApp(config);
    </script>



</body>

</html>

1 ответов


Я считаю, что это невозможно сделать только с помощью одного вызова firebase. Я думаю, вам нужно создать своего пользователя, а затем сделать что-то вроде этого:

firebase.database().ref('users/' + user.uid).set({
  companyName: companyName,
  contact: contact,
  ...
})

или как описано в документации firebase, как это:

var user = firebase.auth().currentUser;

user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});

вместо displayName и photoUrl вы собираетесь использовать свои атрибуты.

редактировать

как вы и просили, я думаю, вы могли бы сделать что-то вроде этого:

firebase.auth().createUserWithEmailAndPassword(email, password).then(function(){
  var user = firebase.auth().currentUser;
  user.updateProfile({
    displayName: "Jane Q. User",
    photoURL: "https://example.com/jane-q-user/profile.jpg"
  }).then(function() {
  // Update successful.
  }, function(error) {
  // An error happened.
 });

})