1

I use this little snippet to get form values:

myForm = document.forms[1];
email = myForm.elements['email']; 

however, if I plan to use this with XHR 2's FormData, I have to do this:

function sendForm() {
  var formData = new FormData();
  formData.append('email', email);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  xhr.send(formData);
}

is there any way to get all form data as one javascript object with which I can use FormData with?

2 Answers 2

2

Just set the form object as the FormData parameter:

function sendForm() {
  var myForm = document.forms[1];
  var formData = new FormData(myForm);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };
  xhr.send(formData);
}

Note: it also works with input type="file"

Sign up to request clarification or add additional context in comments.

Comments

-1

What you can do is, store all the information in an array and append them dynamically.

var myForm = document.forms[1];
var data = {};
data["email"] = myForm.elements["email"];
data["username"] = myForm.elements["username"];
data["password"] = myForm.elements["password"];
//  ... and so on...

now in your send for you can pass the data as argument and append all the data:

function sendForm(data) {
  var formData = new FormData();

  for(var i in data) {
    formData.append(i,data[i]);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) { ... };

  xhr.send(formData);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.