Uploading a file using only Ajax

04 / Jul / 2014 by Mansi Arora 1 comments

We often need to upload a file without refreshing page or even before user submits the complete form.

We have been using flash uploaders or i-frames to achieve that. However now it is possible to upload a file using only ajax and javascript.

The first thing we need is a HTML form that will allow the user to select the file that they wish to upload. Lets create a form with file type in it

In grails, we prefer to use g:form tag

<g:form name="myForm">
   <div>
      <label for="name">
        <strong>Name</strong>
      </label>
   <input id="name" name="name" type="text"/>
  </div>
  <input type="file" name="inputFile">
</g:form>

We can even use a normal form tag:

<form method="post" enctype="multipart/form-data">
   <div>
        <label for="name">
            <strong>Name</strong>
        </label>
        <input id="name" name="name" type="text"/>
   </div>
   <input type="file" id="inputFile"  name="inputFile">
</form>

Now lets include jQuery form plugin which will provide us functionality to upload files using ajax

Now all we need to do is call ajaxSubmit method, which is provided by jQuery form plugin
with options.

<script type="text/javascript">
   $('form').ajaxSubmit({ 
        async: true,
        url: myCustomUrl,
        success : function(){
           ..... // Add your success handler code here
        }
</script>

I also created a demo app, showing this behaviour. Feel free to check it out.

Cheers!

Mansi Arora

mansi[at]intelligrape[dot]com

FOUND THIS USEFUL? SHARE IT

comments (1 “Uploading a file using only Ajax”)

Leave a comment -