AJAX File Upload using Codeigniter, jQuery

I will show you how to upload a file using Codeigniter, AJAX and jQuery without page refresh. This file upload tutorial example is very helpful to implement the upload functionality. In this example the file is selected using the browse button and file is uploaded to the ‘uploads’ directory. Codeigniter controller stores the file into the defined location and returns response as a success or failure message from the controller. As a validation step I have added only to check if you have selected a file for uploading or not.

You may read also AJAX Multiple Files Upload using PHP, jQuery and  AJAX File Upload using PHP, jQuery


Netbeans 8.1
XAMPP in Windows
Codeigniter 3.0.6

Configure XAMPP and Netbeans

From Netbeans IDE go to Tools->Options. Click on PHP. Now on tab “General” browse the file for “PHP 5 Interpreter”. The php interpreter file generally placed inside the <physical drive in Windows OS>:xamppphpphp.exe

Configure Codeigniter and Netbeans

Create a new PHP project in Netbeans. Then remove the index.php file from the newly created project. Now copy the extracted files from Codeigniter 3.0.6 to the newly created project directory.

Directory Structure

A typical directory structure for the project would be as shown below. Here assests directory will contain static resources like css, js, images. uploads directory will hold all uploaded files.

ajax file upload

Step 1. Now modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and session

Step 2. Create a controller file ajaxupload.php under ci3/application/controllers with the following source code

Step 3. Create a view file file_upload_ajax.php under ci3/application/views

Step 4. Modify file ci3/application/config/routes.php file

Step 5. If everything is fine then run the application. You will get the output in the browser.

If you try to upload file without selecting any file then you would see error message “Please choose a file”.

If the file successfully uploaded then you will see success message “File successfully uploaded : uploads/<some-file-name>“.

ajax file upload codeigniter

If the file you are trying to upload already exists then you will see a message “File already exists : uploads/<some-file-name>“.

Hope you have got an idea how to upload file using Codeigniter, AJAX and jQuery.

Thanks for reading.

5 Replies to “AJAX File Upload using Codeigniter, jQuery”

Leave a Reply

Your email address will not be published. Required fields are marked *