Form submit html and js

Viewed 30

After checking with recaptcha I want to send info to another page. If I print in the console the info they are visible but if I send that and I get by post they are undefined

var payload = {
  name: '<?php echo $name ?>',
  email: '<?php echo $email ?>'
};
console.table(payload);
var form = document.createElement('form');
form.style.visibility = 'hidden'; // no user interaction is necessary
form.method = 'POST'; // forms by default use GET query strings
form.action = 'test.php';
for (key in Object.keys(payload)) {
  var input = document.createElement('input');
  input.name = key;
  input.value = payload[key];
  form.appendChild(input); // add key/value pair to form
}
document.body.appendChild(form); // forms cannot be submitted outside of body
form.submit(); // send the payload and navigate

2 Answers

What you are printing in the console is not the same as what you are inserting into the form.

Object.keys gives you an array containing the keys from an object.

key in loops over the keys of an object.

Looking over the keys of an array gives you 0, 1, etc.

payload[key] then gives you payload[0] and payload[1] which are undefined.


Either loop over key in payload or use Object.keys(payload).forEach(...) (or Object.entries(payload).forEach since you want the keys and values anyway).

for ... in already loops over the keys, so key becomes 0 and 1, but of course payload[0] is undefined. I'd recommen using Object.keys(payload).forEach(...) instead:

var payload = {
  name: '<?php echo $name ?>',
  email: '<?php echo $email ?>'
};
console.table(payload);
var form = document.createElement('form');
//form.style.visibility = 'hidden'; // no user interaction is necessary
form.method = 'POST'; // forms by default use GET query strings
form.action = 'test.php';
Object.keys(payload).forEach((key) => {
  var input = document.createElement('input');
  input.name = key;
  input.value = payload[key];
  form.appendChild(input); // add key/value pair to form
});
document.body.appendChild(form); // forms cannot be submitted outside of body
//form.submit(); // send the payload and navigate

I removed the visibility: hidden so we can actually see what happens in the form. Before the change to forEach(), the inputs contained undefined, so that would already have pointed to the issue being getting the correct values from payload.

Related