Solved

submitting multiple forms with one click

Posted on 2014-09-15
13
222 Views
Last Modified: 2014-09-16
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
0
Comment
Question by:M. Jayme Nagy
  • 7
  • 6
13 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40325156
Take a look to this plugin : http://malsup.com/jquery/form/
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 40325177
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40325824
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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 500 total points
ID: 40325837
replace : field
by : $(field)
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326211
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
 
LVL 82

Expert Comment

by:leakim971
ID: 40326227
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326235
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
 
LVL 82

Expert Comment

by:leakim971
ID: 40326313
I will not eat your dog, let it :)
but you right
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326343
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326345
im not sure if the above works
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326355
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 40326367
thanks a lot!!!
BIG HELP
0
 
LVL 82

Expert Comment

by:leakim971
ID: 40326431
:)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question