Archive

Archive for May, 2009

Upload files with jQuery, Ajax and PHP.

May 22, 2009 ppshein Leave a comment

In these days jQuery and Ajax are so popular in web development. One of my clients told me that, they want to upload multiple files without clicking button. That’s why I have had an idea to integrate jQuery, Ajax and PHP.

Download jQuery Here

Download ajax jQuery plugin

Create Upload Button like

<div id="upload_button">Upload</div>

Write following simple coding in your upload form

// You must create it only after the DOM is ready for manipulations
// Use $(document).ready for jquery
// document.observe("dom:loaded" for prototype
new AjaxUpload('upload_button_id', {action: 'upload.php'});

Configure at Ajax Upload

new AjaxUpload('#upload_button_id', {
  // Location of the server-side upload script
  action: 'upload.php',
  // File upload name
  name: 'userfile',
  // Additional data to send
  data: {
    example_key1 : 'example_value',
    example_key2 : 'example_value2'
  },
  // Submit file after selection
  autoSubmit: true,
  // The type of data that you're expecting back from the server.
  // Html (text) and xml are detected automatically.
  // Only useful when you are using json data as a response.
  // Set to "json" in that case.
  responseType: false,
  // Fired after the file is selected
  // Useful when autoSubmit is disabled
  // You can return false to cancel upload
  // @param file basename of uploaded file
  // @param extension of that file
  onChange: function(file, extension){},
  // Fired before the file is uploaded
  // You can return false to cancel upload
  // @param file basename of uploaded file
  // @param extension of that file
  onSubmit: function(file, extension) {},
  // Fired when file upload is completed
  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
  // @param file basename of uploaded file
  // @param response server response
  onComplete: function(file, response) {}
});

Add following coding in your upload form

//You can use these methods, to configure AJAX Upload later.
var upload = new AjaxUpload(‘#div_id’,{action: ‘upload.php’});
//For example when user selects something, set some data
upload.setData({‘example_key’: ‘value’});

//Or you can use these methods directly inside event function
new AjaxUpload(‘div_id’, {
action: ‘upload.php’,
onSubmit: function() {
// allow only 1 upload
this.disable();
}
});
});

Here is server-side script, upload.php

move_uploaded_file($_FILES["file"]["tmp_name"],
“upload/” . $_FILES["file"]["name"]);

Best Credit To : http://valums.com/ajax-upload