3

I am binding jQuery's submit function to the form-Tag. This works fine with one Form, but if I have more than one Form, it submits Data from all Forms in the Post variable.

How can I submit only one Form?

$('form').bind('submit',function() {
    var data = $('form').serializeAnything();
    $.post('forms/form.ajax.submit.php',data,function(response) {
        ...
});
Community
  • 1
  • 1
Dirk Kolbe
  • 59
  • 6
  • You need to customize your selector : $('form'). Try to set an ID to the form, and then use $('form#ID'), or a more complex CSS selector (:first-child, etc) – pistache Oct 24 '12 at 11:05

4 Answers4

3

Use IDs for your forms and use that for data variable.

var data = $('#this_form').serializeAnything();

or traverse by find the parent form like $(this).closest('form').serializeAnything();

Riz
  • 9,703
  • 8
  • 38
  • 54
0
var data;
data=$('form1').serializeAnything();
data+=$('form2').serializeAnything();
data+=$('form3').serializeAnything();
Man Programmer
  • 5,300
  • 2
  • 21
  • 21
0

You can do it using selectors id or class.

e.g.

var data = $( '#formID' ).serializeAnything();

var data = $( '.formCLASS' ).serializeAnything();

Narendra Patel
  • 307
  • 2
  • 12
0

Instead of $('form').serializeAnything(); you want $(this).serializeAnything(); (or, perhaps, $(this).serialize(); if jQuery's standard serialization function will do).

/* attach a submit handler to each form */
$('form').submit(function (event) {

    /* stop form from submitting normally */
    event.preventDefault();

    /* get some values from elements on the page: */
    var $form = $(this),
        form_data = $form.serialize(),
        url = $form.attr('action');

    /* Send the data using post */
    var posting = $.post(url, form_data);
    console.log('finished ajax post');

    /* Put the results in a div */
    posting.done(function (data) {
        console.log('now load response');
        $('#result').empty().append( $(data) );
    });
});

See a working example at http://jsfiddle.net/jhfrench/QjaTq/29/.

Jeromy French
  • 11,812
  • 19
  • 76
  • 129