1

This would be a follow-up of question [A form's “action” and “onsubmit”: Which executes first?][1] where it's concluded that onSubmit runs first, and then the action to submit a form is done.

I would like to compose my onSubmit method to clean up the POST submission that will be sent; is there a way to modify said POST message that will be sent to the server, not by changing the values of the fields, but rather the composition of it?

As an example, my form consists of two fields, name and surname. The submit action ends up sending a POST body like:

name=John&surname=Doe

But I'd like the POST body to be

fullname=John_Doe

I am actually stuck without an idea of how to approach this problem, so any hint on where to look for documentation about this is appreciated - I don't want to leech the code that will do it, but some hint of where to start.

Thanks! [1]: A form's "action" and "onsubmit": Which executes first?_

ggonmar
  • 760
  • 1
  • 7
  • 28

2 Answers2

1

You can achieve this by modifying form-data before sending the request.
But you need to send the request yourself.

const form = document.querySelector("form");

form.addEventListener("submit", e => {
  e.preventDefault();

  let preparedData = new FormData(form);
  preparedData.append(
    "fullName",
    `${preparedData.get("firstName")} ${preparedData.get("lastName")}`
  );

  console.log("Fullname: " + preparedData.get("fullName"));
  var request = new XMLHttpRequest();
  request.open("POST", "http://example.com/submitform.php");
  request.send(preparedData);
});

Example: https://stackblitz.com/edit/js-yia2yg?file=index.js

Sandro Schaurer
  • 416
  • 4
  • 13
0

To stop the form action you can call a onSubmit method:

<form action="/action_page.php" onsubmit="myFunction()">
  Enter first name: <input type="text" name="fname">
  Enter last name: <input type="text" name="lname">
  <input type="submit" value="Submit">
</form>
function myFunction(evt) { 
  evt.preventDefault();

  let data = {
    fullname: //place the data you need to send here
  };

  fetch("/post/data/here", {
    method: "POST", 
    body: JSON.stringify(data)
  }).then(res => {
    console.log("Request complete! response:", res);
  });
};
bamovh
  • 54
  • 5