0

I tried to answer my question here: Submit two forms with one button (but couldn't get it solved)

I have a HTML page displaying a form. I can click an "add more" button and append another form to the page. I want to be able to submit all those forms with a single button.

The initial form has this header:

   <form class = "aform" method = 'POST' action="http://localhost:8080" >

I use this button to submit all the forms:

<input type = "button" value = "Submit" onclick="submitForms()"/>

This is the submitForms() function:

function submitForms() {
  var allforms = document.getElementsByClassName('aform');

  for(var i = 0; i < allforms.length; i++)
    allforms[i].submit();
}

The problem is: only the last form is sent to the json file. If there's only one form, it works fine; if there are two, only the second is sent.

The code is huge, so I'm not sure if I've posted everything relevantt.

EDIT: This is the node.js request

else if (req.method === 'POST' && req.url === '/'){
    var body ='';
    req.on('data', function(data){
      body += data.toString();
    });
    req.on('end', function(){
      var postObj = qs.parse(body);
      console.log(postObj);
      fs.appendFileSync('./data/users.json', JSON.stringify(postObj) + "\n ", function(err) {
        if (err) throw err;
        console.log('Saved!');
        res.end();
      });
Mil3d
  • 31
  • 1
  • 6
  • Create form inside form and send form request data type is json. – DHARMENDRA SINGH Feb 19 '18 at 02:37
  • As mentioned in that old question, a SUBMIT is both a sending of data and a navigation to the submission URL. Chromium and possibly others will discard all but one of your navigations. So, you can only ever submit one form. If you want to have what looks like 2 forms the data really needs to be part of a single form one way or the other. (Hidden variables that copy from forms 2-n, or those other forms really being part of this form). You could also fire off a set of XmlHttpRequests but only if you don't care about the different responses. – Dave S Feb 19 '18 at 02:50
  • I see. Currently, the data is stored as an object and sent to the json file. How would I use a single form to create many objects? – Mil3d Feb 19 '18 at 02:56

0 Answers0