Monday, November 24, 2014

Submit form in jQuery with file input and stay on the same page

You can use Ajax to send the contents of a form to the server asynchronously, so you can stay on the same page. What no one explains is how to do that if you have a file input control. The reason is that neither javascript nor jQuery has access to the contents of the file input control, just the file name. So to upload a form that contains a file input control you have to use ordinary submit, and let the browser do the file upload for you. So all you need is a regular form like:

<form action="/" 
    enctype="multipart/form-data" type="post">
<input type="file" name="file_element"></file>
<input type="submit"></input>
<input id="source" name="source" type="hidden" value=""></input>

Then somewhere in your javascript for the page add the source url to the hidden "source" input:

$( document ).ready(function() {

Now on the server, in the "form_processing" script or servlet, execute a redirect to the address of the original form. In java all you need to do is:


To set the value of "source" you will have to process the multi-part request, which will require a library like Apache commons fileupload, or in php you just read $_POST, and use http_redirect to do the actual redirect. This will submit the form and it will flash, but you'll land back where you came from. No need to jump through hoops or reinvent the wheel.

Reading output

If the url you redirected to produces output you want to display you have to use a different technique. Don't use redirection on the server. Instead, just add a target="myiframe" to the form element. Then add an <iframe name="myiframe"> to the page to receive the output from the submitted-to URL. The output should be a regular HTML page. You can even add a stylesheet to it.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from JQuery Training in Chennai . or learn thru JQuery Training . or learn thru ES6 Online Training. Nowadays JavaScript has tons of job opportunities on various vertical industry.