Course Content
Introduction to CodeIgniter
CodeIgniter is a powerful PHP framework built for developers who need a simple and elegant toolkit to create full-featured web applications.
0/3
MVC (Model-View-Controller)
MVC stands for Model-View-Controller. MVC is an application design model consisting of three interconnected parts. They include the model (data), the view (user interface), and the controller (processes that handle input).
0/6
Sessions
The Session class allows you to maintain a user’s "state" and track their activity while they browse your site.
0/1
URI Routing
There is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:
0/1
Forms and Input
Forms provide a way for users to interact with the application and submit data.
0/1
Composer
Composer is dependency manager in PHP. it allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
0/1
Security
You can enable CSRF protection by modifying your application/config/config.php file
0/1
Working with Database
Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides a rich set of functionalities to interact with the database.
0/5
DataTable
DataTables is a table enhancing plug-in for the jQuery Javascript library that helps in adding sorting, paging, and filtering abilities to plain HTML tables with minimal effort. The main goal is to enhance the accessibility of data in normal HTML tables.
0/1
Spreadsheet
PhpSpreadsheet is a PHP library for reading and writing spreadsheet files. Importing Excel and CSV into MySQL help to save the user time and avoid repetitive work.
0/1
Payment Gateway
Razorpay and PayTM Payment Gateway
0/2
Chatbot
WhatsApp Chatbot and Telegram Chatbot
0/2
CodeIgniter 3
About Lesson

In this post, we will discuss how to upload a file using AJAX in Codeigniter 3. This method allows us to upload files without refreshing the page, providing a seamless user experience.

 

Step 1: Setting Up Codeigniter

First, download and install Codeigniter 3 from the official website. Once installed, configure your base URL and database settings in the application/config directory.

 

Step 2: Creating the Controller

Create a new controller named File_upload.php in the application/controllers directory. This controller will handle the file upload process.

 
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
ini_set('erro_reporting', 0);
#[AllowDynamicProperties]
class File_upload extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        
    }

	public function index() {
		$data 					= [];
		$data ['content_title'] = 'File Upload'; 
		$this->load->view('file_upload/upload', $data);
	}

	function upload_config($path) {
		if (!is_dir($path)) 
			mkdir($path, 0777, TRUE);		
		$config['upload_path'] 		= './'.$path;		
		$config['allowed_types'] 	= '*';
		$config['max_filename']	 	= '255';
		$config['encrypt_name'] 	= TRUE;
		$config['max_size'] 		= 4096; 
		$this->load->library('upload', $config);
	}

	function showSuccessMessage($message) {
	    return '<div class="alert alert-success alert-dismissible" role="alert">
	                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
	                <strong>Great!</strong>
	                '.$message.'
	            </div>';
	}

	function showErrorMessage($message) {
	    return '<div class="alert alert-danger alert-dismissible" role="alert">
	                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
	                <strong>Oh snap!</strong>
	                '.$message.'
	            </div>';
	}

}

 

Step 3: Creating the View

Next, create a new view named upload.php in the application/views/file_upload directory. This view will contain the HTML form for file upload.

<!DOCTYPE html>
<html lang="en">

<head>
	<title><?php echo $content_title; ?></title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>

<body>
	<div class="container mt-5">
		<h2>Upload a File with AJAX Using Codeigniter 3</h2>

		<div class="result"></div>
		
		<form id="form-upload-file" method="post" autocomplete="off" enctype="multipart/form-data">
			<div class="form-group">
				<label>Attachment</label>
				<input type="file" class="form-control" name="file" id="attachment" placeholder="Attachment">
			</div>
			<div class="form-group">
				<button type="submit" id="btn-upload" class="btn btn-primary">Upload</button>
			</div>
			<div class="form-group file-result">
			</div>
		</form>
	</div>

	<script>
		$(document).ready(function() {
			$("body").on("submit", "#form-upload-file", function(e) {
				e.preventDefault();
				var data = new FormData(this);
				$("#btn-upload").prop('disabled', true);
				$.ajax({
					type 			: 'POST',
					url 			: '<?php echo base_url("file/upload"); ?>',
					data 			: data,
					dataType		: 'json',
					contentType		: false,
					cache			: false,
					processData		:false,
					beforeSend		: function() {
						$("#btn-upload").prop('disabled', true);
					}, 
					success 		: function(result) {
						if($.isEmptyObject(result.error_message)) {
							$(".result").html(result.success_message);
							$(".file-result").html(result.html);
						} else {
							$(".result").html(result.error_message);
						}
						$("#btn-upload").prop('disabled', false);
					}
				});
			})
		});
	</script>
</body>
</html>

 

Step 4: Handling the AJAX Request

Finally, we need to handle the AJAX request in the do_upload function of our File_upload.php. This function will process the uploaded file.

 

public function upload() {
		$path 		= 'documents/';
		$this->upload_config($path);
		if (!$this->upload->do_upload('file')) {
			$json = [
				'error_message' => $this->showErrorMessage($this->upload->display_errors()),
			];
		} else {
			$file_data 	= $this->upload->data();
			$file_name 	= $path.$file_data['file_name'];
			$json 		= [
				'success_message'	=> $this->showSuccessMessage('File has been uploaded successfully.'),
				'html'				=> '<a href="'.base_url($file_name).'" target="_blank">See Your file</a>',	
			];
		}
		echo json_encode($json);
	}

 

Step 5: Define Routes

$route['file/upload/example'] = 'File_upload/index';
$route['file/upload'] = 'File_upload/upload';

 

File-Upload Output

 

That’s it! You have now set up a simple file upload system using AJAX in Codeigniter 3.