Uploading file to codeIgniter 4 using AJAX is very easy, just need to pass server URL, method and data in AJAX method and it return response in json without refresh web page.
Let’s start by creating a ajax file upload feature in codeIgniter application:
Step 1 – Set up CodeIgniter 4
To download CodeIgniter 4 from the official website, Link:
Extract downloaded zip file in xampp/htdocs
directory. and edit app/Config/App.php
file, and set up base url in it:
public $baseURL = 'http://localhost/your-project/public';
Step 2 – Create File Upload Form
Go to app/Views
directory, and create a view file named upload_form.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX File Upload</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>AJAX File Upload</h1>
<form id="upload-form" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit">Upload</button>
</form>
<div id="response"></div>
</body>
</html>
Step 3 – Add Ajax in Form
Add ajax code in upload_form.php
to upload file from form to server without refresh web page:
<script>
$(document).ready(function () {
$('#upload-form').on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
$('#response').html('<p>' + response.message + '</p>');
} else {
$('#response').html('<p>' + response.errors.file + '</p>');
}
}
});
});
});
</script>
Step 4 – Create Controller Class
Create a controller file named UploadController.php
in app/controllers
directory, and create methods in it to handle file upload on server using ajax on server:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class UploadController extends Controller
{
public function index()
{
return view('upload_form');
}
public function upload()
{
$validationRule = [
'file' => [
'label' => 'File',
'rules' => 'uploaded[file]|mime_in[file,image/jpg,image/jpeg,image/gif,image/png]|max_size[file,2048]',
],
];
if (! $this->validate($validationRule)) {
return $this->response->setJSON(['success' => false, 'errors' => $this->validator->getErrors()]);
}
$file = $this->request->getFile('file');
if ($file->isValid() && ! $file->hasMoved()) {
$newName = $file->getRandomName();
$file->move(WRITEPATH . 'uploads', $newName);
return $this->response->setJSON(['success' => true, 'message' => 'File uploaded successfully.']);
}
return $this->response->setJSON(['success' => false, 'message' => 'File upload failed.']);
}
}
Step 5 – Define Routes
Edit app/Config/Routes.php
and define the routes to handle ajax file upload requests:
$routes->get('/', 'UploadController::index');
$routes->post('upload', 'UploadController::upload');
Step 6 – Test Application
Run the following command to start application server:
cd /your-project
php spark serve
Open your browser and access file upload feature in application by typing http://localhost:8080/
url in browser.