Wednesday, June 18, 2014

How to Upload Files with CodeIgniter and AJAX?

Uploading files asynchronously with CodeIgniter can be confusing and frustrating experience. In this tutorial I will share the steps how I successfully implemented a file upload with CodeIgniter and ajax.

You need CodeIgniter, jQuery, and the script AjaxFileUpload which you can copy from bottom of this tutorial.

It's assumed you have a working knowledge of CodeIgniter and jQuery. But no prior knowledge of AjaxFileUpload is necessary. It is also assumed that you already have successfully set up CodeIgniter. For the sake of brevity and clarity, we are not going to use database to save file information.

Step 1. Creating a form
Create your view and name it upload.php. This view will contain our upload form.

At the top; jQuery, AjaxFileUpload, and our own custom javascript files are loaded.
Then, we created a standard HTML form. The empty #files div is where the confirmation/failure message will be displayed.Step 2. Custom Javascript
Create custom.js inside 'js' folder and Place the following code:

The JavaScript hijacks the form submit and AjaxFileUpload takes over. In the background, it creates an iframe and submits the data via that.
We then check our return (which will be in JSON). Depending on the status(success/error), we display message.Step 3. Uploading a FileThe Controller
The URL we are uploading to is /upload/upload_file/, so create a new method in the upload controller, and place the following code in it.