CodeIgniter 4 Upload Image using Ajax Method

Share this Article
Reading Time: 10 minutes
2,151 Views

CodeIgniter 4 is a open source PHP Framework. Inside this article we will cover CodeIgniter 4 Upload Image with Form data using Ajax Request Tutorial. Nowadays, every application somewhere uses Ajax request either for any database operations. It’s common feature now.

Inside this tutorial create a form with input type file and see the functions step by step to upload by using Ajax Request. Already we have article over form data upload by using Ajax, Click here to learn.

Upload image using ajax in CodeIgniter 4 is a very interesting topic and easy to learn here.

Learn More –

  • Image Upload with Preview Using Ajax in CodeIgniter 4, Click here.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system.

To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.


Create Database & Table in Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create a table with some columns.

CREATE TABLE students (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(120) DEFAULT NULL,
email varchar(120) DEFAULT NULL,
mobile varchar(45) DEFAULT NULL,
profile_image varchar(150) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table.

Next, connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Add Routes

Open Routes.php file from /app/Config folder. Add these routes into it.

//...

$routes->get("add-student", "StudentController::addStudent");
$routes->post("save-student", "StudentController::saveStudent"); 

Let’s create Model.


Create Model

Open project into terminal and run this spark command to create model file.

$ php spark make:model Student --suffix

It will create StudentModel.php file at /app/Models folder. Open file and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class StudentModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'students';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name", 
		"email", 
		"mobile",
        "profile_image"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Controller

Back to terminal and run this spark command to create controller.

$ php spark make:controller Student --suffix

It will creates StudentController.php file inside /app/Controllers folder.

Open StudentController.php and write this complete code into it.

<?php

namespace App\Controllers;

use App\Models\StudentModel;

class StudentController extends BaseController
{
	public function __construct()
	{
		helper(["url"]);
	}
	public function addStudent()
	{
		// layout of add student form
		return view('add-student');
	}

	public function saveStudent()
	{
		if ($this->request->getMethod() == "post") {

			$rules = [
				"name" => "required",
				"email" => "required|valid_email",
				"mobile" => "required",
				"profileImage" => [
					"rules" => "uploaded[profileImage]|max_size[profileImage,1024]|is_image[profileImage]|mime_in[profileImage,image/jpg,image/jpeg,image/gif,image/png]",
					"label" => "Profile Image",
				],
			];

			if (!$this->validate($rules)) {

				$response = [
					'success' => false,
					'msg' => "There are some validation errors",
				];

				return $this->response->setJSON($response);
			} else {

				$file = $this->request->getFile('profileImage');

				$profile_image = $file->getName();

				// Renaming file before upload
				$temp = explode(".",$profile_image);
				$newfilename = round(microtime(true)) . '.' . end($temp);

				if ($file->move("images", $newfilename)) {

					$studentModel = new StudentModel();

					$data = [
						"name" => $this->request->getVar("name"),
						"email" => $this->request->getVar("email"),
						"mobile" => $this->request->getVar("mobile"),
						"profile_image" => "images/" . $newfilename,
					];

					if ($studentModel->insert($data)) {

						$response = [
							'success' => true,
							'msg' => "Student created successfully",
						];
					} else {

						$response = [
							'success' => false,
							'msg' => "Failed to create student",
						];
					}

					return $this->response->setJSON($response);
				} else {

					$response = [
						'success' => false,
						'msg' => "Failed to upload Image",
					];

					return $this->response->setJSON($response);
				}
			}
		}
	}
}
  • if ($this->request->getMethod() == “post”) {} Checking request type
  • $rules = []; Defining input field validation rules
  • if (!$this->validate($rules)) {} Validating form values with validation rules
  • $file = $this->request->getFile(‘profileImage’); Reading file from submitted form data
  • if ($file->move(“images”, $newfilename)) {} Create images folder inside /public folder. Storing images inside that folder
  • if ($studentModel->insert($data)) {} Saving form data to database table.
  • return $this->response->setJSON($response); Sending response in JSON format

Create Image Folder

As we are uploading image from form. move() method in codeigniter 4 will upload image into /images folder.

It will be created automatically inside /public folder. But in case if you are getting error about file upload path, then you can create images folder inside /public folder.


Create Layout File

Go to /app/Views folder.

Create a file add-student.php inside it.

Open add-student.php file and write this complete code into it.

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

<head>
    <title>CodeIgniter 4 Upload Image using Ajax Method</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.2/dist/sweetalert2.min.css" rel="stylesheet" />
    <style>
        #frm-add-student label.error{
            color:red;
        }
    </style>
</head>

<body>

    <div class="container">
        <h4 style="text-align: center;">CodeIgniter 4 Upload Image using Ajax Method</h4>
        <div class="panel panel-primary">
            <div class="panel-heading">CodeIgniter 4 Upload Image using Ajax Method</div>
            <div class="panel-body">
                <form class="form-horizontal" enctype="multipart/form-data" action="javascript:void(0)" id="frm-add-student">
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="name">Name:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" required id="name" placeholder="Enter name" name="name">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="email">Email:</label>
                        <div class="col-sm-10">
                            <input type="email" class="form-control" required id="email" placeholder="Enter email" name="email">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="mobile">Mobile:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" required id="mobile" placeholder="Enter mobile" name="mobile">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2" for="profileImage">Profile Image:</label>
                        <div class="col-sm-10">
                            <input type="file" accept="image/*" required class="form-control" id="profileImage" name="profileImage">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>

</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Validation library file -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>
<!-- Sweetalert library file -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9.17.2/dist/sweetalert2.min.js"></script>

<script>
    $(function() {

        // Adding form validation
        $('#frm-add-student').validate();

        // Ajax form submission with image
        $('#frm-add-student').on('submit', function(e) {

            e.preventDefault();

            var formData = new FormData(this);

            //We can add more values to form data
            //formData.append("key", "value");

            $.ajax({
                url: "<?= site_url('save-student') ?>",
                type: "POST",
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                dataType: "JSON",
                success: function(data) {
                    if (data.success == true) {
                        Swal.fire('Saved!', '', 'success')
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    alert('Error at add data');
                }
            });
        });
    });
</script>
  • $(‘#frm-add-student’).validate(); Adding client side form validation
  • $(‘#frm-add-student’).on(‘submit’, function(e){}) This code is going to submit formdata to server
  • $.ajax({}); Using Ajax Method of jquery.
  • e.preventDefault(); It prevents from default behaviour

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/add-student.

Submitting form without data

Provide value to form & submit form

Data saved into database table

We hope this article helped you to learn CodeIgniter 4 Upload Image Using Ajax Request in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here