Jquery ajax file upload not working

I  have an existing code  which saves the form inputs  through Jquery ajax this way ...

$.ajax({
    			type : "POST",
    			url : actionUrl,
    			data : $('form').serialize(),
    			async: false,
    			cache : false,
    			dataType : "html",
    			success : function(responseText) {
    				//success message
    			}
    		});   

Open in new window


although the above code  saves  the form text fields but  it  does not  save  file field  .  How do I upload  file ? What changes I may require in my code to include file upload ?

I would like to do minimum changes to my existing code.  Could please you suggest an workaround  and example ?
cofactorAsked:
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.

Mukesh YadavFull Stack DeveloperCommented:
0
Alexandre SimõesManager / Technology SpecialistCommented:
AFAIK, it's not possible to upload files through AJAX in a way all browsers support it (IE < 10).

To make it work, you need to rely on FormData that is an HTML5 property.

If supporting older versions of IE is not a requirement for you then the proposed solution should work:
$("form#data").submit(function() {
    var formData = new FormData($(this)[0]);
    $.post($(this).attr("action"), formData, function() {
        // success    
    });
    return false;
});

Open in new window

(Code taken from the SO link above posted by: @Mukesh Yadav)

If you need to handle big files and/or low bandwidth, you better go for a solution that allows you chinking and a better control
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
cofactorAuthor Commented:
I need this to work  with Internet Explorer only for versions

IE9
IE10
IE11

Could anyone please suggest best fitting solution with my present  code ?
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

cofactorAuthor Commented:
comments please.
0
Alexandre SimõesManager / Technology SpecialistCommented:
Well, in this case your only option is to post the form the old fashioned way.

Depending on the size of the files, maybe it's a good idea to use a file upload component like http://www.plupload.com/
With these components you can handle chunking easier and even if the user submits the form before the upload is finished, just catch the file uploaded event and submit the form through AJAX.

This way you can even control if the file upload failed or not.

Of course this requires changes to your code... and quite a few.
For the least amount of changes, just submit the whole form without AJAX.
0
cofactorAuthor Commented:

For the least amount of changes, just submit the whole form without AJAX.

I am changing the code from submitting whole form to  ajax way submit !  .... there is no going back.


Well, in this case your only option is to post the form the old fashioned way.

Depending on the size of the files, maybe it's a good idea to use a file upload component like http://www.plupload.com/

I have looked at it.  It seems to me your example requires HTML 5   support  ..... So this may not work in IE9 ....... I am also using jSP  not PHP  as  I find  example in the site.

again , I am still looking for  a work around to save  the form fields & files  in ajax way  in IE9 , IE10 , IE11  browser.

Is  there any other workaround ?
0
Alexandre SimõesManager / Technology SpecialistCommented:
It seems to me your example requires HTML 5 support
It supports fallback if HTML5 is not available. And this one is just an example, here another very well known jquery based file uploaded: https://blueimp.github.io/jQuery-File-Upload/

And you missed the piece of information that is actually your solution if you still want to submit the form through AJAX:  
... just catch the file uploaded event and submit the form through AJAX
This means that internally you have to submit the form in two steps (for the user should still be a single save button click):
1- Upload the file
2- Wait for the successful update and Submit the form

The only trick is to upload the file in a way it can later be associated with the form that the server still doesn't know about. In this case, GUIDs are your friend :)
0
cofactorAuthor Commented:


... just catch the file uploaded event and submit the form through AJAX


 I need  simple code snippet for this.  I would like to give this a  try.  Could you please post a code snippet for this ?
0
Alexandre SimõesManager / Technology SpecialistCommented:
I think the best is if you have a look at the documentation of the plugins.
For instance, this last one I mentioned, here's a simple demo from their documentation:
https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin
In this example you'll see the 'done' callback handler, that will be called after a successful upload.

Here's the API documentation page (pointing to the 'done' callback):
https://github.com/blueimp/jQuery-File-Upload/wiki/Options#done

I think the main example is enough for your scenario.
0
cofactorAuthor Commented:
Ok....I am trying with IE 11 browser  with FormData   but getting error here
            

            Processing of multipart/form-data request failed. Stream ended unexpectedly<br/>
            
javax.servlet.ServletException: Processing of multipart/form-data request failed. Stream ended unexpectedly
		at org.apache.struts.upload.CommonsMultipartRequestHandler.handleRequest(CommonsMultipartRequestHandler.java:242)
		at org.apache.struts.util.RequestUtils.populate(RequestUtils.java:1209)
		at org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:821)
		at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:254)
		at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
		at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525) 

Open in new window


            
            
            JSP (Struts)
            --------------
            
<html:form action="/s/planAdd" enctype="multipart/form-data"  styleId="planForm1"
		method="POST"> 
		 

Open in new window


                 JAVASCRIPT
               
		var form = $('form')[0];
	        var formdata = false;
	         
		  if (window.FormData){
           	         formdata = new FormData(form);
           	         alert("ie11 test3");
           	 }
		    

		    $.ajax({
        			type : "POST",
        			url : actionUrl,
        			data : formdata, 
        			async: false,
        			cache : false,
        		        processData : false,
        	                contentType : false,
        			beforeSend : function(){    				
        				var msg = $('<div/>').addClass('ajax-auto-save-msg').html('Saving the data...');
        		      	$('body').append(msg); 
        			},
        			success : function(responseText) {
        				setTimeout(function() {
        		      		$('.ajax-auto-save-msg').remove();
        		      	}, 10000);
        				$('#ajaxDiv').html(responseText);
        			}
        		});   

Open in new window

0
Alexandre SimõesManager / Technology SpecialistCommented:
But you said before that you need to support IE9.
FormData is only available on IE10+

http://caniuse.com/#search=formdata
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
JSP

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.