kamikaze_pilot
kamikaze_pilot

Reputation: 14834

ajax submit multiple forms via jquery

so suppose I have 3 forms

<form name="form1">
<input name="input"></input>
<submit></submit>
</form>

<form name="form2">
<input name="input"></input>
<submit></submit>
</form>

<form name="form3">
<input name="input"></input>
<submit></submit>
</form>

Each of the form has its own submit button

now suppose I have another form

<form id="submitAll">
<submit value="submit all"></submit>
</form>

whose sole function is to submit all the other 3 forms simultaneously....now here are the constraints:

  1. when submitAll is submitted, it has to do so using Ajax and forward the input data from all the other 3 forms to processor.php preferably via POST
  2. processor.php needs to be able to distinguish between which inputs go to which form...and then process the inputs of each form separately

My question is....what is be the best way to make processor.php be able to distinguish which inputs belong to which form.....

My previous attempts was to use jquery's serialize to serialize all the 3 forms' inputs, but then it would merge all the inputs into one string and notice that since the inputs in the forms have the same name, the string goes like "input=blah&input=blah&input=blah" and I can't distinguish between which input goes to which form.....

It is highly preferable to have the inputs in the forms to have the same name so that processor.php can execute smoothly

Is there away to make POST strings be passed as arrays or json or any other format so that processor.php can distinguish which input goes to which form without making the input names differ? remember it needs to do so via Ajax

thanks in advance!!!

Upvotes: 1

Views: 6535

Answers (3)

RobertPitt
RobertPitt

Reputation: 57268

<form name="form1" class="postable"></form>
<form name="form2" class="postable"></form>
<form name="form3" class="postable"></form>

javascript:

$(document.ready(function(){
    $("a.submitforms").click(function(){
       $('form.postable').each(function(){
           Form = $(this);
           payload = $(Form).serialize();

          //Send payload via Ajax.
       });
    });
}));

This is just an alternative method but I agree with Ish Kumar's Method!

Upvotes: 0

Ish
Ish

Reputation: 29536

Why don't you use naming convention like

  • name="Form1[input]"
  • name="Form2[input]"
  • name="Form3[input]"

then do regular serialize and $.post, this will help you keep the same naming convention in processor loop

EDIT:

<?php 
foreach($_POST as $form) {
     // $form = array('input' => 'i am here')
     processForm($form); // names are still the same for all forms
}
?>

Upvotes: 2

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Wouldn't you want to use an array? The inputs would be in the order they were serialized.

<input name="input[]" />

Upvotes: 1

Related Questions