I will show you an example on Ajax file upload using codeigniter 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 also like to read below tutorials on file upload examples:

AJAX Multiple Files Upload using PHP, jQuery

AJAX File Upload using PHP, jQuery

Prerequisites

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 Ajax file upload using codeigniter jquery 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 using codeigniter jquery

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

This is one time activity and once you load you can use uniformly throughout the application code.

$autoload['helper'] = array('html', 'url', 'file', 'form');

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

This controller class is responsible for handling request and response of clients and any validation or business logic as applicable.

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of ajaxupload
 *
 * @author https://roytuts.com
 */
class AjaxUpload extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->load->view('file_upload_ajax', NULL);
    }

    function upload_file() {

        //upload file
        $config['upload_path'] = 'uploads/';
        $config['allowed_types'] = '*';
        $config['max_filename'] = '255';
        $config['encrypt_name'] = TRUE;
        $config['max_size'] = '1024'; //1 MB

        if (isset($_FILES['file']['name'])) {
            if (0 < $_FILES['file']['error']) {
                echo 'Error during file upload' . $_FILES['file']['error'];
            } else {
                if (file_exists('uploads/' . $_FILES['file']['name'])) {
                    echo 'File already exists : uploads/' . $_FILES['file']['name'];
                } else {
                    $this->load->library('upload', $config);
                    if (!$this->upload->do_upload('file')) {
                        echo $this->upload->display_errors();
                    } else {
                        echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
                    }
                }
            }
        } else {
            echo 'Please choose a file';
        }
    }

}

Step 3. Create a view file file_upload_ajax.php under ci3/application/views. Here we have shown how to use ajax file upload using codeigniter jquery.

This file is responsible for giving user options to select and upload file.

The below view file has one input button for file type and another button for submission once the file is selected for uploading.

Then we catch the button’s onClick event through jQuery and upload the file at appropriate destination in the server location.

Finally we display either success or failure message as we receive from the server through success or error methods respectively.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>AJAX File upload using Codeigniter, jQuery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function (e) {
                $('#upload').on('click', function () {
                    var file_data = $('#file').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: 'http://localhost/ci3/index.php/ajaxupload/upload_file', // point to server-side controller method
                        dataType: 'text', // what to expect back from the server
                        cache: false,
                        contentType: false,
                        processData: false,
                        data: form_data,
                        type: 'post',
                        success: function (response) {
                            $('#msg').html(response); // display success response from the server
                        },
                        error: function (response) {
                            $('#msg').html(response); // display error response from the server
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="msg"></p>
        <input type="file" id="file" name="file" />
        <button id="upload">Upload</button>
    </body>
</html>

Step 4. Modify file ci3/application/config/routes.php file because we want our above controller class to be default to load the view file for uploading file.

$route['default_controller'] = 'ajaxupload';

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 using codeigniter jquery

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 on ajax file upload file using Codeigniter  jQuery.

Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

6 thoughts on “AJAX File Upload using Codeigniter, jQuery

Leave a Reply

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