简体   繁体   中英

Posting data to Firebase using a form

I have a simple form with inputs:

<body>
    <div class="jumbotron">
    <div class="placeholder"></div>
    </div>
    <div class="container">
            <h2>Add a new Animal</h2>
    <form class="form-group" id="add-animals">
    Species: <input type="text" id="species" class="form-control">
    Name: <input type="text" id="name" class="form-control" >
    Age: <input type="text" id="age" class="form-control">
    Last Fed: <input type="date" id="last-fed" class="form-control">
    Last Shed: <input type="date" id="last-shed" class="form-control">
    Diet: <input type="text" id="diet" class="form-control">
    Basking area temperature: <input type="text" id="basking-area-temperature" class="form-control">
    Cold part temperature: <input type="text" id="cold-temperature" class="form-control">
    Humidity: <input type="text" id="humidity" class="form-control">
    Addition Info: <textarea class="form-control" id="additional-info"></textarea>
    <button id="btnCreate" class="btn btn-primary">Create</button>
    </form>
    <h3>View Current Animals</h3>
    <ol id="animal-list">

    </ol>
    </div>
    </div>
    <script>
  // Initialize Firebase
  var config = {
    apiKey: "AIzaSyBSuC8nqJzLe7d5jKS-_nE15kaI9Y6NIfI",
    authDomain: "repti-care-32176.firebaseapp.com",
    databaseURL: "https://repti-care-32176.firebaseio.com",
    projectId: "repti-care-32176",
    storageBucket: "repti-care-32176.appspot.com",
    messagingSenderId: "632910932105"
  };
  firebase.initializeApp(config);
  const db = firebase.firestore();
  db.settings({ timestampsInSnapshots: true }); 
</script>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>

    <script src="./scripts/main.js"></script>
</body>

And I want to add new entries to my database when the form is submitted, here is my js:

const animalList = document.querySelector('#animal-list');
const form = document.querySelector('#add-animals');


function renderAnimals(doc) {
let li = document.createElement('li');
let name = document.createElement('div');
let species = document.createElement('div');
let age = document.createElement('div');
let last_fed = document.createElement('div');
let last_shed = document.createElement('div');
let diet = document.createElement('div');
let basking_area_temp = document.createElement('div');
let cold_part_temp = document.createElement('div');
let humidity = document.createElement('div');
let additional_info = document.createElement('div');

li.setAttribute('data-id', doc.id);
name.textContent = `name: ${doc.data().name}`
species.textContent = `species: ${doc.data().species}`
age.textContent = `age: ${doc.data().age}`
last_fed.textContent = `last fed: ${doc.data().last_fed}`;
last_shed.textContent = `last shed: ${doc.data().last_shed}`;
diet.textContent = `diet: ${doc.data().diet}`;
basking_area_temp.textContent =`basking area temp: ${ doc.data().basking_area_temp}`;
cold_part_temp.textContent =  `cold part temp: ${doc.data().cold_part_temp}`;
humidity.textContent = `humidity: ${doc.data().humidity}`;
additional_info.textContent = `additional info: ${doc.data().additional_info}`;

li.appendChild(species);
li.append(name);
li.append(age);
li.append(last_fed);
li.append(last_shed);
li.append(diet);
li.append(basking_area_temp);
li.append(cold_part_temp);
li.append(humidity);
li.append(additional_info);

animalList.appendChild(li);
}

// getting data from the back end
db.collection('animals').get().then((snapshot) => {
snapshot.docs.forEach(doc => {
    renderAnimals(doc);
  })
})

// adding data
form.addEventListener('submit', (event) => {
    event.preventDefault();
    db.collection('animals').add({
        species: form.species.value,
        name: form.name.value,
        age: form.age.value,
        last_fed: form.last_fed.value,
        last_shed: form.last_shed.value,
        diet: form.diet.value,
        basking_area_temp: form.basking_area_temp.value,
        cold_part_temp: form.cold_part_temp.value,
        humidity: form.humidity.value,
        additional_info: form.additional_info.value

    })
})

Currently when I add the information to my form fields it fires off an error:

Cannot read property 'value' of undefined at HTMLFormElement.form.addEventListener (main.js:58)

why is my last_fed object property undefined and how can I fix this so that the data gets posted to the database? For some reasons there happens to be a problem only with the variables that have a "_" sign in them, if I remove them everything works fine

You're initializing form like this:

const form = document.querySelector('#add-animals');

And then in the submit-handler you do:

species: form.species.value

The form.species doesn't point to anything. There is nothing in the DOM that allows you to look up the fields in a form by their ID like that.

You'll need to look up each field from the HTML with a query selector. So for this line:

species: document.querySelector("species").value

Note that this type of problem is easy to troubleshoot once you put a breakpoint in the code that throws an error, and hit it with a breakpoint. From there you can inspect the form variable and see that it doesn't have a species property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM