Waqar Ali
Waqar Ali

Reputation: 106

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

Upvotes: 0

Views: 2241

Answers (2)

mplungjan
mplungjan

Reputation: 178350

The JSON in the title does not seem to be relevant

  1. Change the link to a submit button
  2. Add a submit event handler that copies the data
  3. Allow the submit to send to server

$("#invoice-form").on("submit", function(e) {
  let data = $('p').text()
  $("#input").val(data)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> the text i want to send </p>
<form action="url" id="invoice-form">
  <input type="text" name="input" id="input">
  <input type="submit">
</form>

If you want to Ajax the value, just change to this

$("#invoice-form").on("submit", function(e) {
  e.prevenDefault();
  let data = $('p').text()
  $.post(this.action,{"input":data})
});

Upvotes: 0

Jack Dunleavy
Jack Dunleavy

Reputation: 287

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

Upvotes: 2

Related Questions