upload images on server side and save url in mysql database

for my codeigniter 3 view page i have a form submission to get new data to sql tale in phpmyadmin:

<div class="container mt-5">
    <button class="btn btn-primary" data-toggle="modal" data-target="#directorModal">Add Director</button>

    <!-- Modal -->
    <div class="modal fade" id="directorModal" tabindex="-1" aria-labelledby="directorModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="directorModalLabel">Add Director</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                <form id="directorForm" method="get" enctype="multipart/form-data" action='<?=$user_base_url?>/profil/save_directors'>
                    <div class="form-group">
                        <label for="director_name">Director Name</label>
                        <input type="text" class="form-control" name="director_name" required>
                    </div>
                    <div class="form-group">
                        <label for="info">Info</label>
                        <textarea class="form-control" name="info" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="position">Position</label>
                        <input type="text" class="form-control" name="position" required>
                    </div>
                    <div class="form-group">
                        <label for="director_image">Director Image</label>
                        <input type="file" class="form-control" name="director_image" required>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">Save</button>
                </form>
                </div>
            </div>
        </div>
    </div>
</div>

here i try to get new user info to save in sql table as well their images in server.

in controller i have following:

public function save_directors() {
    $this->load->library('upload');
    $config['upload_path'] = './uploads/board_of_directors_images/';
    $config['allowed_types'] = 'gif|jpg|png|jpeg'; // Adjust as needed
    $config['max_size'] = 2048; // 2MB max size
    $config['encrypt_name'] = TRUE; // Encrypt the file name
    $this->upload->initialize($config);
    if ($this->upload->do_upload('director_image')) {
        $upload_data = $this->upload->data();
        $director_image = $upload_data['file_name'];
    } else {
        $error = $this->upload->display_errors();
        log_message('error', 'Image upload error: ' . $error);
        $director_image = NULL; // Set to NULL or handle accordingly
    }
    $director_data = [
        'director_name' => $this->input->get('director_name'),
        'info' => $this->input->get('info'),
        'position' => $this->input->get('position'),
        'director_image' => $director_image
    ];
    $this->db->insert('board_of_directors', $director_data);
    if ($this->db->affected_rows() > 0) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error']);
    }
}

and tha ajax in view page:

$(document).ready(function() {
    $('#directorsForm').on('submit', function(event) {
        event.preventDefault(); // Prevent the form from submitting the traditional way

        // Create a FormData object to hold the form data, including the file
        var formData = new FormData(this);
        $.ajax({
            url: '<?=$user_base_url?>/profil/save_directors', // Adjust the URL according to your setup

            type: 'GET',
            data: formData,
            processData: false,  // Important! Prevent jQuery from automatically transforming the data into a query string
            contentType: false,  // Important! Prevent jQuery from overriding the content type
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Director saved successfully!');
                    // Optionally, redirect or refresh the page
                } else {
                    alert('Failed to save director.');
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX error:', error);
                alert('An error occurred while saving the director.');
            }
        });
    });
});

i use get as the post return error. i fill the form and upload an image but i have recieved :

You did not select a file to upload.

any one can help how should i resolve that?

1. File Input Field:

  • Ensure Correct Name: Double-check that the name attribute of the file input field (name="director_image") matches the name you’re using in your controller’s $this->upload->do_upload() method.
  • Accept Attribute: If you want to restrict the file types that can be uploaded, set the accept attribute on the file input field. For example:
    HTML
<input type="file" class="form-control" name="director_image" required accept="image/jpeg, image/png, image/gif">

2. FormData Object:

  • When using FormData to submit the form, ensure that the file is correctly added to the object. You can use the following approach:

JavaScript

var formData = new FormData(this);
formData.append('director_image', $('#director_image')[0].files[0]);

3. Controller Upload Configuration:

  • Verify that the upload configuration in your controller’s $this->upload->initialize($config) method is correct. Ensure the upload_path is accessible and the allowed_types are set to match the accepted file types.

4. Form Submission Method:

  • While you’re using GET for testing, it’s recommended to use POST for form submissions, especially when uploading files. This ensures that the file data is sent correctly to the server.

Revised Controller Code:

PHP

public function save_directors() {
    $this->load->library('upload');
    $config['upload_path'] = './uploads/board_of_directors_images/';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = 2048;
    $config['encrypt_name'] = TRUE;
    $this->upload->initialize($config);

    if ($this->upload->do_upload('director_image'))    1.  github.com github.com {
        $upload_data = $this->upload->data();
        $director_image = $upload_data['file_name'];

        // ... rest of your code for saving data to the database
    } else {
        $error = $this->upload->display_errors();
        log_message('error', 'Image upload error: ' . $error);
        $director_image = NULL; // Set to NULL or handle accordingly
    }

    // ... rest of your code for saving data to the database
}

Revised AJAX Code:

JavaScript

$(document).ready(function() {
    $('#directorsForm').on('submit', function(event) {
        event.preventDefault();

        var formData = new FormData(this);
        formData.append('director_image', $('#director_image')[0].files[0]);

        $.ajax({
            url: '<?=$user_base_url?>/profil/save_directors',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            // ... rest of your AJAX code
        });
    });
});

By making these adjustments, you should be able to successfully upload the director image and save the data to your database.