1

When submitting my form, It just refreshes the page and adds a question mark at the end of the URL. However, when I enter this into the console, the code runs perfectly. Any ideas?

document.querySelector('form').onsubmit = function() {

      const rec = document.querySelector('#compose-recipients').value;
      const sub = document.querySelector('#compose-subject').value;
      const bod = document.querySelector('#compose-body').value;
    
      fetch('/emails', {
        method: 'POST',
        body: JSON.stringify({
            recipients: rec,
            subject: sub,
            body: bod
        })
      })
      .then(response => response.json())
      .then(result => {
          // Print result
          console.log(result);
      });
    load_mailbox('sent');
    return false;
  }
j08691
  • 190,436
  • 28
  • 232
  • 252
arajan2
  • 11
  • 1
  • Are there an errors in the developer console when the page loads? My guess https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – epascarello Jan 21 '21 at 18:02
  • $10 says you're loading the script before the DOM is ready. – Jared Smith Jan 21 '21 at 18:03

2 Answers2

1

Fetch is an asynchronous API. It is an modification to original XMLHttpRequest API. Now, default behavior of submit button event is to refresh the page. So when you submit the form, the default behavior kicks in. So the Fetch API is not able to make any query to server. That means you have to prevent the default submission behavior in order to make that query.

Two ways to achieve the desired behavior.

  1. Add a regular button and on clicking the button try to send the query.

  2. Or, try using preventDefault to stop the page from being refreshed (override the default behavior).

       document.querySelector('form').onsubmit = function(e) {
    
           e.preventDefault() // override the default behavior
    
           const rec = document.querySelector('#compose-recipients').value;
           const sub = document.querySelector('#compose-subject').value;
           const bod = document.querySelector('#compose-body').value;
    
           fetch('/emails', {
             method: 'POST',
             body: JSON.stringify({
                 recipients: rec,
                 subject: sub,
                 body: bod
             })
           })
           .then(response => response.json())
           .then(result => {
               // Print result
               console.log(result);
           });
         load_mailbox('sent');
         return false;
       }
    

adds a question mark at the end of the URL

Form submission enforce the browser to perform a query (as expected). So browser accepts some query parameters. But it gets none. That's why an empty question marks is being added by the browser at the end of url.

Update : Also provide full url path in fetch requst.

AL-zami
  • 7,637
  • 11
  • 53
  • 104
  • I have tried each of these options, and it still will not post the "emails" to the /emails route. Copying and pasting the same code into the console works though, so I am confused. – arajan2 Jan 21 '21 at 19:51
  • try to give full url like yourdomain/emails . Is your page refresh problem solved? – AL-zami Jan 22 '21 at 06:01
  • Hi, I have just resolved the issue by giving the full url. Thank you so much! – arajan2 Jan 24 '21 at 19:03
  • If it helps consider selecting it as an answer – AL-zami Jan 24 '21 at 19:21
0

After this line

document.querySelector('form').onsubmit = function(e) {

add this

event.preventDefault();

This will prevent the page from reloading

centralhubb.com
  • 2,141
  • 16
  • 14