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

2

6

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>
Bigelow answered 11/4, 2016 at 3:17 Comment(0)
P
11

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.

Pica answered 11/4, 2016 at 3:47 Comment(1)
What is dataRef contains here ? I am not be able to get login method success event as i am able to add user with createUserWithEmailAndPassword in javascript web.Ampoule
A
0

Thanks Frank! and here is the modified version of @Frank answer for ES6 using arrow function:

dataRef.set("I'm writing data", error => {
  if (error) {
    alert("Data could not be saved." + error);
  } else {
    alert("Data saved successfully.");
  }
});
Achromatism answered 2/2, 2020 at 7:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.