Skip to content
Advertisement

How to append data to request form.submit()

I am trying to submit a form using POST, but I have some additional data from <p> tags that I have stored into JS object. I want to send that to server when I hit form.submit() from JavaScript.

<p> the text i want to send </p>
<form action="url" id="invoice-form">
    <input type="text" name="input"> 
</form>


Edit:[Updated Title]
<a id="submit" type="button">Submit</a>

<script>
let data = $('p').text()

$('#invoice-form').submit()

What I am trying to do is to send data with submit event

Advertisement

Answer

You could attach an onclick handler to the button and use fetch to send the data in JSON format to the server.

const onclick = (e) => {
  const data = {
    data: document.querySelector('input').value
  }


  e.preventDefault();

  fetch("/server-end-point", {
    method: 'POST',
    mode: 'no-cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
}

const button = document.querySelector('#submit');

button.onclick = onclick;
<p> the text i want to send </p>
<form action="url" id="invoice-form">
    <input type="text" name="input"> 
    <button id="submit" type="button">Submit</button>
</form>

More info about Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Is fetch supported in your browser targets: https://caniuse.com/fetch

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement