Speed up development with full-stack environments for every branch.

Learn More

Detecting if data exists in Firebase [JavaScript]

Forked from How to use the jQuery $().ready function.

411 Runs 6310 Views 1481 Copies
Saved

Saved

sundip 66

sundip
published 3 years ago

<html>
  <head>
  
    <!-- Installing Firebase from CDN -->
    <script src='https://cdn.firebase.com/v0/firebase.js'></script>
    
    <script type="text/javascript">
    /* Recipe code to check if data exists in Firebase */
    
      function go() {
        var userId = prompt('Username?', 'Guest');
        checkIfUserExists(userId);
      }
 
      var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
       
      function userExistsCallback(userId, exists) {
        if (exists) {
          alert('user ' + userId + ' exists!');
        } else {
          alert('user ' + userId + ' does not exist!');
        }
      }
       
      // Tests to see if /users/<userId> has any data. 
      function checkIfUserExists(userId) {
        var usersRef = new Firebase(USERS_LOCATION);
        usersRef.child(userId).once('value', function(snapshot) {
          var exists = (snapshot.val() !== null);
          userExistsCallback(userId, exists);
        });
      }
      
    </script>
    <link rel="stylesheet" href="runnable.css" />
  </head>
  <body>
    <h1>Check if a username exists in Firebase Chat example</h1>
    <p><a href="#" onclick="go();">Click here</a> to check if a username exists</p>
  </body>
</html>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).