Unable to transfer Firebase data onclick

So, I recently messed around with Firebase, and I ran into a problem, I need some help. Therefore, I am trying to send data from user input to Firebase, and for this data it will be displayed in the specified div, but the data does not appear in my Firebase or in this div ...

Here is my HTML code:

<form>
    <input name="name" class="form-control" type="name" placeholder="Title" id="titleInput" />
    <br/>
    <textarea id="postInput" name="content" data-provide="markdown" rows="10"></textarea>
    <hr/>
    <button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>

And my jQuery code (EDITED):

function submitPost() {
     var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
     var name = $('#titleInput').val();
     var text = $('#postInput').val();
     myDataRef.push({name: name, text: text});
     $('#postInput').val('');

     myDataRef.on('child_added', function(snapshot) {
          var post = snapshot.val();
          displayUserPost(post.name, post.text);
     })
     function displayUserPost(name, text) {
         $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
         $('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
     }
 };
+4
source share
1 answer

You are dealing with an asynchronous data stream, so you must listen to the data outside of the submitPost function.

var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
myDataRef.on('child_added', function(snapshot) {
  var post = snapshot.val();
  displayUserPost(post.name, post.text);
});

function submitPost(e) {
  var myDataRef = new Firebase('https://EXAMPLE.firebaseio.com/');
  var name = $('#titleInput').val();
  var text = $('#postInput').val();
  myDataRef.push({name: name, text: text});
  $('#postInput').val('');
  e.preventDefault();
}

function displayUserPost(name, text) {
  $('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#PostsDiv'));
  $('#PostsDiv')[0].scrollTop = $('#PostsDiv')[0].scrollHeight;
}
+5
source

Source: https://habr.com/ru/post/1619051/


All Articles