1

The moment I enter the username . It gives the alert message that message has been sent before even entering the message and data is being stored in the database with username and empty message . I cannot understand Why ? Can anyone help me with the question . Any help would be appreciated.

const firebaseConfig = {};
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
const username = prompt('Enter your username');

function sendMessage() {

  const messageinput = document.getElementById("messageInput");
  const message2 = messageinput.value;;
  db.ref('User_messages').set({
      "message": message2,
      "username": username
    })
    .then(() => {
      alert('Message sent to the database');
    })
}
document.getElementById('messageBtn').addEventListener('click', sendMessage());
<form id="message-form">
  <input id="messageInput" type="text" placeholder=" Enter Your Doubt Here" />
  <button id="messageBtn" type="submit">Send</button>
</form>
</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Remove the `()` after `sendMessage` in `addEventListener()`. It's calling the function immediately, not when the event happens. – Barmar Apr 12 '22 at 18:09
  • @Barmar by doing that and writing the message , it again prompts for Enter the user name. – ANSHU JOSHI Apr 12 '22 at 18:11
  • You have the prompt in the top-level code, not in the function. So it's executed when the page loads, not when you click. – Barmar Apr 12 '22 at 18:12
  • yeah the problem is it is not getting stored in the database and prompting to enter data again again after clicking the send button. It should show the alert that data has been sent. – ANSHU JOSHI Apr 12 '22 at 18:14
  • The way you've written it, it should only prompt for the username once, when you load the page. If you fix it as I said, each time you click the button it should send the message to the database and then show the alert. – Barmar Apr 12 '22 at 18:17
  • Yeah , thats the issue I am facing – ANSHU JOSHI Apr 12 '22 at 18:20
  • What's the issue? The linked question explains how to fix the fact that the alert is coming immediately. What other issue are you having? – Barmar Apr 12 '22 at 18:22

0 Answers0