Submitting a form through Javascript via POST method

410 Views Asked by At

index.js

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('#compose').addEventListener('click', compose_email);

  document.querySelector('#compose-form').onsubmit = send_email;
  // By default, load the inbox
  load_mailbox('inbox');
});

function compose_email() {

  // Show compose view and hide other views

  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 = '';
  
}


function send_email()
{
  const recipients = document.querySelector('#compose-recipients').value;
  const subject = document.querySelector('#compose-subject').value;
  const body = document.querySelector('#compose-body').value;
  //console.log(recipients)

  fetch('/emails', {
    method: 'POST',
    body: JSON.stringify({
        recipients: recipients,
        subject: subject,
        body: body,
    })
  })
  .then(response => response.json())
  .then(result => {
      // Print result
      console.log(result);
});
}

inbox.html

<div id="compose-view">
    <h3>New Email</h3>
    <form id="compose-form">
        <div class="form-group">
            From: <input disabled class="form-control" value="{{ request.user.email }}">
        </div>
        <div class="form-group">
            To: <input id="compose-recipients" class="form-control">
        </div>
        <div class="form-group">
            <input class="form-control" id="compose-subject" placeholder="Subject">
        </div>
        <textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
        <input type="submit" class="btn btn-primary"/>
    </form>
</div>

Submitting a form through Javascript via POST method but I am getting an output of GET /? HTTP/1.1" 200 1667 in terminal.. It should be 201 via POST

When I am writing the fetch function in Console.It is working fine

After submitting the form it is just returning back to the inbox page.

1

There are 1 best solutions below

3
On BEST ANSWER

Since you are doing a "fetch" in your code, you should prevent the default form submission on the "submit" button click (This this the default behaviour). To achieve this you can receive the "event" as a parameter in the "send_email" function and then do a "event.preventDefault()".

function send_email(event) {
   // Your code
   ...
   // Prevent the default form submission
   event.preventDefault();
}

More details @ https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit