Roy Vincent Niepes

Blog and Portfolio

Posted on by

Sending multiple forms using jQuery Ajax


Sending multiple forms using jQuery Ajax

Are you having a problem how you can use the jQuery ajax with multiple forms?
We’ll I did, I’ve encountered this problem during my development with unfamiliar language, jsp. My task was to re-skin and apply the psd to the site, however the design has a drastic changes with the previous design in regards to its features.

This the old form displayed in a popup window

This is the new form where clicking the add button will add a new line of form.

Ideally the input should just be an array inside a one form, but since the site only accept a non array field, I have to deal with it through ajax.(jsp developer will have never had this problem since they can change the servlet function, unlike me, even just printing hello world is a pain)

Enough with my story here’s how you could do it.

Put same class on the forms and put a class on the button that will submit a form

<form class="ajax_form" method="post" action="servlet/save"></form>
<form class="ajax_form" method="post" action="servlet/save"></form>
<form class="ajax_form" method="post" action="servlet/save"></form>
<input type="button" class="submitforms" />
<script>
$(document).ready(function(){


/* this is our ajax function created for an arrayed forms */
var called = 0;
ajax_recaller = function(forms){
$.ajax({
type: "POST",
data: forms[called].serialize(),                             // to submit fields at once
url: forms[called].attr('action'),                        // use the form's action url
success: function(data) {
called++;                                                                        // this will serve as a key

if(called < forms.length) {
ajax_recaller(forms);                                            // call the ajax function again
} else {
called=0;                                                                    // set called value to 0 again
alert('All forms has been submitted!');
}

}
});

}


$(document).on('click','.submitforms',function(){
var x=0;

$('.ajax_form').each(function(){
forms[x] = $(this);
x++;
});

ajax_recaller(forms);
});

});
</script>

Hope it helps! Happy coding and Advance happy holidays! 🙂

Before coming up with this idea, I tried to use jquery $.when function first, this also works however its not realiable, sometimes it doesn’t save all the data submitted from the forms.
From 5 forms submited it randomly saves 2 to 5 of it.

If you were curious of the code, I got it from stackoverflow, searching on how to submit multiple forms using ajax.

comments powered by Disqus