0

I am new to JS. I'm testing form and intentionally sending HTTP POST request with incorrect credentials. Server responds me with JSON object which contains a message. I want to put this message below the field in which user entered incorrect data. I receive JSON object and I'm able to use it's content for example in console, but as I try to modify the DOM and insert this message under the field I'm being redirected to the root (/?) of my website. I want to stay on current page instead and be able to modify it. I tried to use Chrome debugger This is the function which makes fetch request.

function compose_email() {

  // Show compose view and hide other views
  document.querySelector('#emails-view').style.display = 'none';
  document.querySelector('#compose-view').style.display = 'block';

  // Clear out composition fields
  document.querySelector('#compose-recipients').value = '';
  document.querySelector('#compose-subject').value = '';
  document.querySelector('#compose-body').value = '';

  // Send email
  document.querySelector("#compose-form").onsubmit = function() {
    let composeView = document.querySelector("#emails-view");

    fetch('/emails', {
      method: 'POST',
      body: JSON.stringify({
        recipients: document.querySelector("#compose-recipients").value,
        subject: document.querySelector("#compose-subject").value,
        body: document.querySelector("#compose-body").value
      })
    })
    .then(response => response.json())
    .then(result => {
      let p = `<p>${result.error}</p>`;
      composeView.append(p);
      alert(result.error);
    })
  }
}
Alex
  • 153
  • 7

0 Answers0