CodeIgniter Ajax File Upload using jQuery
Submitted by nurhodelta_17 on Thursday, February 15, 2018 - 22:46.
Installing CodeIgniter
If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this tutorial. After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP. Then, you can test whether you have successfully installed codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_fileupload_ajax so I'm using the below code.- localhost/codeigniter_fileupload_ajax

Creating our Database
First we are going to create our database. 1. Open your phpMyAdmin. 2. Create a new database named codeigniter. 3. Click the database that we created, click SQL tab then paste the below code or import the included .sql file in the downloadable of this source code located in db folder.Connecting our App into our Database
Next, we're going to connect our codeigniter application to the database that we created earlier. 1. In your codeigniter app folder, open database.php located in application/config folder. 2. Update database.php with your credential the same as what I did in the image below. database is where we define the database that we created earlier.
Configuring Base URL
Next, we configure our base url to tell codeigniter that this is the URL of our site/application. We're gonna be using this a lot that's why we need to configure this. 1. In your codeigniter app folder, open config.php located in application/config folder. 2. Find and edit the ff line:- $config['base_url'] = 'http://localhost/codeigniter_fileupload_ajax/';
Creating our Model
Next, we create the model for our app. Take note that the first letter of your model name should be in CAPITAL letter and the name of the model should be the same as the file name to avoid confusion. Create a file named Files_model.php in application/models folder of our app and put the ff codes.- <?php
- class Files_model extends CI_Model {
- function __construct(){
- parent::__construct();
- $this->load->database();
- }
- public function getAllFiles(){
- $query = $this->db->get('files');
- return $query->result();
- }
- public function insertfile($file){
- return $this->db->insert('files', $file);
- }
- }
- ?>
Creating our Controller
Next step is to create our controller. Controllers follow the same naming convention as models. Create a file named Upload.php in application/controllers folder of our app and put the ff codes.- <?php
- class Upload extends CI_Controller {
- function __construct() {
- parent::__construct();
- //load our helper
- $this->load->helper('url');
- //load our model
- $this->load->model('files_model');
- }
- public function index(){
- $this->load->view('file_upload');
- }
- public function fetch(){
- $result = $this->files_model->getAllFiles();
- foreach($result as $row){
- ?>
- <tr>
- <td><?php echo $row->id; ?></td>
- <td><?php echo $row->filename; ?></td>
- <td><img src="<?php echo 'upload/'.$row->filename; ?>" height="30px" width="30px"></td>
- </tr>
- <?php
- }
- }
- public function insert(){
- $config['upload_path'] = 'upload/';
- $config['file_name'] = $_FILES['file']['name'];
- $config['allowed_types'] = 'gif|jpg|png|jpeg';
- $this->load->library('upload', $config);
- $this->upload->initialize($config);
- if($this->upload->do_upload('file')){
- $uploadData = $this->upload->data();
- $filename = $uploadData['file_name'];
- $file['filename'] = $filename;
- $query = $this->files_model->insertfile($file);
- if($query){
- $output['message'] = 'File uploaded successfully';
- }
- else{
- $output['error'] = true;
- $output['message'] = 'File uploaded but not inserted to database';
- }
- }else{
- $output['error'] = true;
- $output['message'] = 'Cannot upload file';
- }
- }else{
- $output['error'] = true;
- $output['message'] = 'Cannot upload empty file';
- }
- }
- }
Defining our Default Controller
Next, we are going to set our default controller so that if no controller is defined, this default controller will be used. Open routes.php located in application/config folder and set the default route to our user controller.- $route['default_controller'] = 'upload';
Creating our Views
Lastly, we create the views of our app. Create the ff files inside application/views folder. file_upload.php- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>CodeIgniter Ajax File Upload</title>
- <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
- <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
- </head>
- <body>
- <div class="container">
- <h1 class="page-header text-center">CodeIgniter Ajax File Upload</h1>
- <div class="row">
- <div class="col-sm-4">
- <h3>File Upload Form</h3>
- <form id="uploadForm">
- <div class="form-group">
- <label>File:</label>
- <input type="file" name="upload" id="file">
- </div>
- <button type="submit" class="btn btn-primary">Save</button>
- </form>
- <div id="responseDiv" class="alert text-center" style="margin-top:20px; display:none;">
- <button type="button" class="close" id="clearMsg"><span aria-hidden="true">×</span></button>
- <span id="message"></span>
- </div>
- </div>
- <div class="col-sm-8">
- <table class="table table-bordered table-striped">
- <thead>
- <tr>
- <th>ID</th>
- <th>Filename</th>
- <th>Preview</th>
- </tr>
- </thead>
- <tbody id="tbody">
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <script type="text/javascript">
- $(document).ready(function(){
- fetchTable();
- $('#uploadForm').submit(function(e){
- e.preventDefault();
- var url = '<?php echo base_url(); ?>';
- var reader = new FileReader();
- reader.readAsDataURL(document.getElementById('file').files[0]);
- var formdata = new FormData();
- formdata.append('file', document.getElementById('file').files[0]);
- $.ajax({
- method: 'POST',
- contentType: false,
- cache: false,
- processData: false,
- data: formdata,
- dataType: 'json',
- url: url + 'index.php/upload/insert',
- success: function(response){
- console.log(response);
- if(response.error){
- $('#responseDiv').removeClass('alert-success').addClass('alert-danger').show();
- $('#message').html(response.message);
- }
- else{
- $('#responseDiv').removeClass('alert-danger').addClass('alert-success').show();
- $('#message').html(response.message);
- fetchTable();
- $('#uploadForm')[0].reset();
- }
- }
- });
- });
- $('#clearMsg').click(function(){
- $('#responseDiv').hide();
- });
- });
- function fetchTable(){
- var url = '<?php echo base_url(); ?>';
- $.ajax({
- method: 'POST',
- url: url + 'index.php/upload/fetch',
- success: function(response){
- $('#tbody').html(response);
- }
- });
- }
- </script>
- </body>
- </html>
Add new comment
- 1261 views