Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submitting multiple forms with AJAX

I have a page which contains several forms. I want to add a single submission button that will allow all the forms to be saved at the same time, as illustrated below:

<form id="form1" name="form1" action="someAction" method="post">
    ....form fields
</form>

<form id="form2" name="form2" action="someOtherAction" method="post">
    ....form fields
</form>

<form id="form2" name="form2" action="anotherAction" method="post">
    ....form fields
</form>

<a href="somewhere.html" onclick="submitAll();">Submit All Forms</a>

<script>
    function submitAll() {
        document.form1.submit();
        document.form2.submit();
        document.form3.submit();
    }
</script>

The issue I'm having is that once the first form gets submitted, it is redirecting the page to that form's destination - I want to intercept that redirect so that I can process the next form.

I know that this can be done via AJAX, which would somehow allow me to catch the returned page (and ignore it if I so choose), but I can't figure out how to do this without mapping each of the fields in the form manually.

Can anyone help?

like image 299
Elie Avatar asked Nov 03 '11 16:11

Elie


1 Answers

This should submit each form via ajax without having to map the fields yourself:

$('form').each(function() {
    var that = $(this);
    $.post(that.attr('action'), that.serialize());
});
like image 134
Richard Dalton Avatar answered Oct 20 '22 22:10

Richard Dalton