Ajax file upload with jQuery

Created on September 22nd, 2009 by Chocksy in Tutorial
JQUERY upload plugin

JQUERY upload plugin

Sometimes we come into a problem that is a little harder to do when it comes to customizing and that is the file upload input. Well Andris Valums helps us with a plugin he created for jQuery.

The plugin requires jQuery 1.2 or above and allows users to upload multiple files without refreshing the page.

To make the plugin work you have to include jQuery and the plugin in your websites head.

%MINIFYHTMLeed0dd17cee928d553c55e204bacc5d211%%MINIFYHTMLeed0dd17cee928d553c55e204bacc5d212%

And after that you can add this for a div with a specific id:

$(document).ready(function(){

$.ajax_upload('#div_id', {
  // Location of the server-side upload script
  action: 'upload.php',
  // File upload name
  name: 'userfile',
  // Additional data to send
  data: {
    key1 : 'value',
    key2 : 'value2'
  },
  // Fired when user selects file
  // You can return false to cancel upload
  onSubmit: function(file, extension) {},
  // Fired when file upload is completed
  onComplete: function(file, response) {},
  // Fired when server returns the string
  onSuccess: function(file){},
  // Fired when server return something else
  onError: function(file, response){}
});

});

And after that just upload the file using:

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "success";
} else {
  echo "error";
}

You can find more info on: http://valums.com/projects/ajax-upload/ or check out the demo page : Demo

Tags: ,