3

EDIT: I want to save input data from my form into Firebase database

The input with id="field0" and button with onClick"submitPost()"

<form>
<input id="field0" name="ePost" type="text" value="">
<button type="submit" class="btn" onclick="submitPost()">Submit</button>
</form>

Cannot put the firebase.js into the head. So solved it like this. If I add the snippets one by one into the console it seems to work. But get an error when I load them all in the console at the same time.

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "https://cdn.firebase.com/v0/firebase.js";
document.head.appendChild(script);

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

function submitPost(e) {
var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
var name = $('#field0').val();
myDataRef.push({name: name});
$('#field0').val('');
}

Here is the above example: https://jsfiddle.net/hbaecklund/7mnns4dk/5/

Do I need to do async loading of the script in order to work? But below doesn't work?

$.ajax({
  url: 'https://cdn.firebase.com/v0/firebase.js',
  dataType: 'script',
  cache: true,
  success: function() {  
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
    myDataRef.on('child_added', function(snapshot) {
    var post = snapshot.val();
    });
    function submitPost(e) {
    var myDataRef = new Firebase('https://eloquatest.firebaseio.com/');
    var name = $('#field0').val();
    myDataRef.push({name: name});
    $('#field0').val('');
    };    
  }
});
2
  • You can use requirejs Commented Apr 13, 2016 at 7:59
  • The thing is that you are submiting the form. You should avoid it and send data to firebase using relevant method. But still, why cannot you just include firebase script in head? Commented Apr 13, 2016 at 8:06

1 Answer 1

1

Try this, by using the load event of the script tag: https://jsfiddle.net/7mnns4dk/6/

Basically just use:

script.load = function() {
  // enter code that needs the script to be loaded here
}

Also it works with jQuery as you wrote it, just move the submitPost function so that it is accessible by the button: https://jsfiddle.net/7mnns4dk/7/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.