submitting multiple forms with one click

Hi,

I have created a page using a third party library that requires me to create four forms to four create tabs. I was using AJAX to process the forms all together using serialize. However, i recently added a fourth form as strictly one file input and noticed that AJAX has problems with this sort of input. I did a little research and people suggested that creating a FormData object would alleviate the file problem.  i tried adapting my original code but

Original Code:
//SUBMIT THE FORMS
	submitForms = function(text){
		
		//TEST TO MAKE SURE THERE IS A FILE
		var file = $('#avatar').val();
		if( (file !='') || (file.length > 0) ){
		
			var dataString = $("#form1, #form2, #form3, #form4").serialize();
			$.ajax( {
			  type: 'POST',
			  url: 'ajax/reg.php' + '?' + text,
			  data: dataString,
			  success: function(data) {
				  $('#message').html(data);
				  
				console.log(data);
			  } 
			})
		
		}
	}

Open in new window


I tried changing dataString to
var dataString = new FormData("#form1, #form2, #form3, #form4");

it got an error (unfortunately, im not on my computer right now so im not exactly sure what the error is)

I tried just creating the FormData object with no params and got the same error so i think i am using it wrong.

I do not necessarily need ajax to process the form. I have all the actions of the form set to the current page so i could do the processing there. However i would need a way to submit all four forms. i was thinking

<?php
//THE USER LANDS ON PAGE
if(empty($_POST)){
//DISPLAY FORMS 

//USED JQUERY TO SUBMIT ALL FOUR FORMS
}else{
//PROCESS FORMS  

}
?>

<script>

$('#final_btn').on("click", function(e){
    var file = $('#avatar').val(); //test to make sure there is a value in the file input
    if( (file !='') || (file.length > 0) ){

        $('#form1').submit();
        $('#form2').submit();
        $('#form3').submit();
        $('#form4').submit();

   }
});

</script>

Open in new window


I have not tried the above code

any help or suggestions would be much appreciated

thanks

Jayme
LVL 6
J NUnicorn wranglerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
Take a look to this plugin : http://malsup.com/jquery/form/
0
leakim971PluritechnicianCommented:
Else try this :

var formdata = new FormData();
jQuery.each($(':file')[0].files, function(i, file) {
    formdata.append('file-'+i, file);
});
jQuery.each($('[name]').not(":file"), function(i, field) {
   formdata.append(field.attr("name"), field.val());
});
			$.ajax( {
                          contentType: false,
                          processData: false,
			  type: 'POST',
			  url: 'ajax/reg.php' + '?' + text,
			  data: formdata,
			  success: function(data) {
				  $('#message').html(data);
				  
				console.log(data);
			  } 
			})

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
J NUnicorn wranglerAuthor Commented:
Hi,

I tried your second function and converted it to this

submitForms = function(text){
        //TEST TO MAKE SURE AVATAR IS NOT EMPTY
        var file = $('#avatar').val();
        if(text =='finish'){
    		if( (file !='') || (file.length > 0) ){
    			return;
                alert('fail');
            }
    	}
        
        var formdata = new FormData();
        jQuery.each($(':file')[0].files, function(i, file) {
            formdata.append('file-'+i, file);
        });
        jQuery.each($('[name]').not(":file"), function(i, field) {
           formdata.append(field.attr("name"), field.val());
        });
        
        $.ajax( {
          contentType: false,
          processData: false,
          type: 'POST',
          url: 'ajax/reg.php' + '?' + text,
          data: formdata,
          success: function(data) {
              $('#message').html(data);
              
            console.log(data);
          } 
        });
    }

Open in new window


this function  give me an error on the following line

formdata.append(field.attr("name"), field.val());

which spits out
TypeError: field.attr is not a function
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

leakim971PluritechnicianCommented:
replace : field
by : $(field)
0
J NUnicorn wranglerAuthor Commented:
Hi,

i just noticed that on my select form input the js is only passing the last option and not the value the user has selected. do you know why>?
0
leakim971PluritechnicianCommented:
replace :
        jQuery.each($('[name]').not(":file"), function(i, field) {
           formdata.append(field.attr("name"), field.val());
        });

Open in new window

by :
jQuery.each($("#form1, #form2, #form3, #form4").not(":file").serializeArray(), function(i, field) {
      formdata.append(field.name, field.value);
})

Open in new window

0
J NUnicorn wranglerAuthor Commented:
Additionally, i only need to upload one file so i do not think i need the each loop on the file or do i?
0
leakim971PluritechnicianCommented:
I will not eat your dog, let it :)
but you right
0
J NUnicorn wranglerAuthor Commented:
HI,

Im not exactly sure what you mean

should i change
        jQuery.each($(':file')[0].files, function(i, file) {
            formdata.append('file-'+i, file);
        });

Open in new window


so that it only accepts one file?
something like
 formdata.append($(':file')[0].files);

Open in new window


im not sure if the above
0
J NUnicorn wranglerAuthor Commented:
im not sure if the above works
0
J NUnicorn wranglerAuthor Commented:
Got it !

i changed
 jQuery.each($(':file')[0].files, function(i, file) {
            formdata.append('file-'+i, file);
        });

Open in new window

to
formdata.append('avatar', $(':file')[0].files[0]);

Open in new window


and it seems to work fine.
0
J NUnicorn wranglerAuthor Commented:
thanks a lot!!!
BIG HELP
0
leakim971PluritechnicianCommented:
:)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.