Upload form data using Ajax Codeigniter

ajax-codeigniter
Ajax Codeigniter

Hello Friends,

Most of beginner developers faces issue when submitting form data with images using ajax and codeigniter. So we are here to help them and resolve the issue.

In this tutorial i have used Codeigniter version 3, and here is the source code of this tutorial.

Database Structure

We have used Database name as Sample in this tutorial and table name as Data.

We have 5 fields in the tutorial, (id, color, name, description, files) and obviously you can add more fields according to your requirement.

Table’s exact structure screenshot is given below

database

View page source code

We have location this code in views/front/home.php

Markup
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Upload form data using ajax in codeigniter</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" />
    
    <style>
        .container{
            display: flex;
            justify-content: center;
        }

        .container form{
            margin: 100px;
        }

        .container form .boxes{
            margin: 15px 0px;
        }
    </style>
</head>
<body>
    <div class="container">
        <form method="post" id="postForm">
            <h1>Upload form data using ajax in codeigniter</h1>
            <div class="boxes">
                <select class="form-control" name="color" id="color" required>
                    <option value="">Select Color</option>
                    <option value="red">Red</option>
                    <option value="blue">Blue</option>
                    <option value="green">Green</option>
                </select>
            </div>
            <div class="boxes">
                <input class="form-control" type="file" name="files[]" id="files" accept="image/*" multiple required>
            </div>
            <div class="boxes">
                <input class="form-control" type="text" name="name" id="name" placeholder="Name" required>
            </div>
            <div class="boxes">
                <textarea class="form-control" name="description" id="caption" placeholder="Description" required></textarea>
            </div>
            <input type="submit" class="form-control btn btn-primary submit_btn" value="Submit">
        </form>
    </div>
    

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script>
        $('#postForm').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: "<?php echo BASE_URL.'post/uploadFormData'; ?>",
                data: new FormData(this),
                dataType: 'html',
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function(){
                    $('.submit_btn').attr('disabled', 'disabled');
                    $('#postForm').css('opacity', '0.5');
                },
                success: function(response){
                    $('#postForm').css('opacity', '1');
                    $('.submit_btn').removeAttr('disabled');
                    alert(response);
                    window.location.href = '';
                }
            });
        });
    </script>
</body>
</html>

Controller source code

We have put given code in controllers/post.php

*Create ‘images’ folder to store images, in public_html directory or your localhost directory.

Markup
<?php
ob_start();
defined('BASEPATH') OR exit('No direct script access allowed');

class Post extends CI_Controller {

	function __construct(){
		
		parent::__construct();
		$this->load->model('post_model');
		$this->load->database();
	}

	/*  Home Page   */
	public function index(){
		$this->load->view('front/home');
	}

	public function uploadFormData(){
		$color 			= $this->input->post('color');
		$name 			= $this->input->post('name');
		$description 	= $this->input->post('description');
		
		$uploadDir = 'images/';

		if($color || $name || $description){
			$filesArr = $_FILES['files'];
			$filesJson = json_encode($filesArr['name']);

			foreach($filesArr['name'] as $key => $val){
				$fileName = basename($filesArr['name'][$key]);
				$target = $uploadDir . $fileName;
				
				$fileType = pathinfo($target, PATHINFO_EXTENSION);
				if(move_uploaded_file($filesArr['tmp_name'][$key], $target)){
					$response = 'Form submitted successfully';
					$uploadStatus = 1;
				}
			}

			if($uploadStatus == 1){
				$upload_db_data = array(
					'color' 		=> $color,
					'name' 			=> $name,
					'description' 	=> $description,
					'files' 		=> $filesJson,
				);

				$result = $this->post_model->insert_data($upload_db_data);

				if($result){
					echo $response;
				}
			}
		}
	}	
}
?>

Model source code

We have put given code in models/post_model.php

Markup
<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class Post_Model extends CI_Model {

    public function insert_data($formData){
        return $this->db->insert('data', $formData);
    }

}
?>

Tutorials List