javascriptfirebasepolymer-1.0firebase-realtime-database

How do I check if a firebase push event was successful on form submit


Here is my polymer form and javascript. It pushes well. What I want to do is check if it was successful, and I will hide the form and show some confirmation text or redirect users to another page..,

So, how do I check if a firebase push was successful or not?

<form is="iron-form" method="get" action="firebaseURL/events" id="eventsDemo">
  <paper-input name="name" label="Name" required auto-validate></paper-input>
  <paper-input name="password" label="Password" type="password" required auto-validate></paper-input>
  <paper-checkbox name="read" required>You must check this box</paper-checkbox><br>
  <paper-button raised onclick="_delayedSubmit(event)" disabled id="eventsDemoSubmit">
    <paper-spinner id="spinner" hidden></paper-spinner>Submit</paper-button>
  <div class="output"></div>
</form>   
<script>
function _delayedSubmit(event) {
    event.preventDefault();
    spinner.active = true;
    spinner.hidden = false;
    eventsDemoSubmit.disabled = true;
    // Simulate a slow server response.
    setTimeout(function() {
      //Polymer.dom(event).localTarget.parentElement.submit();
      var firebase = new Firebase(eventsDemo.getAttribute('action'));
      firebase.push(eventsDemo.serialize());
    }, 100);
  }
</script>

Solution

  • Every write method in Firebase can take an optional completion listener, which will be called one the write operation has been completed on the server. From the documentation on completion callbacks:

    If you'd like to know when your data has been committed, you can add a completion callback. Both set() and update() take an optional completion callback that is called when the write has been committed to the database. If the call was unsuccessful for some reason, the callback will be passed an error object indicating why the failure occurred.

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

    I recommend reading the Firebase guide for web programmers end to end. It contains many useful tidbits that will save you (and us) many hours down the line.