5

I have a form. This form submits via POST to an iframe, that, in turn, has the request processed and, depending on the result, a javascript is executed that changes the parent's content according the the submission's validity.

Now, I don't like this procedure. I want the ability to submit several forms simultaneously, but I have only this one hidden iframe. So I would like to do it with AJAX, creating a separate request for each form submission.

However, my form is complicated; it consists of checkboxes that add variables to arrays, of images that are clicked and whose click coordinates I need sent, and complicated stuff like that - which is why I, instead of calculating each the value of each input and adding it to a post parameter string (by the way: I don't know how I can create arrays that way), I would much prefer to rather have the submission content intercepted, saved as a post string with all those parameters, and then use this string for the AJAX POST request.

That I would like to do in this function:

$('#myForm').submit(function(event){

    // process the submission, e. g. event.getContent().toPostString();

    // create the AJAX request and send it and attach listeners (I know how to do this line ;)

    return false; // I don't want the form submitted (to the iframe)

});

Thanks in advance!

arik
  • 28,170
  • 36
  • 100
  • 156

2 Answers2

7

Don't use an iframe, just use jQuery's ajax methods: (I used post() in the example below)

$('#myForm').submit(function(event){

             //url          //post data
    $.post(this.action, $(this).serialize(), function(returnData){
           //do something with returnData
    })

    return false; //do not submit form the normal way

});

Here is an example: http://jsfiddle.net/maniator/Y6r8E/
Type something into the form and submit it.

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • Perfect! Amazing! Wow, just what I needed! – arik Jun 15 '11 at 19:38
  • Except for one thing, I just noticed. If using images as submit buttons, neither click position (which would not be so terrible), but not even the clicked image (if using several images as potential submission buttons) is passed. – arik Jun 15 '11 at 19:51
  • @arik is it in the form? anything that is in the form is passed thru. just output the `$(this).serialize()` to check – Naftali Jun 15 '11 at 19:52
  • Well, it is in the form, or at least, it should be. However, as already stated, it is not passed :( (I checked, it's not in the serialization of the form, either). But never mind, I just thought it's worth mentioning ;) – arik Jun 15 '11 at 19:59
  • @arik -- ok. you can always add more params by appending `+'&param=somevalue&param2=somevalue'` after the serialization – Naftali Jun 15 '11 at 20:00
1

jQuery's serialize() function will gather the form data for you, to allow for easy form submission via .ajax() or .post().

George Cummins
  • 28,485
  • 8
  • 71
  • 90