upload image using codeigniter with ajax and formdata

upload image using codeigniter with ajax and formdata

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging Image Upload Failures in CodeIgniter: A FormData Guide

When implementing image uploads using CodeIgniter, jQuery, and AJAX, a common point of failure occurs when the form submission seems to hang or redirect unexpectedly. The symptoms described—where the page redirects, database values fail to insert, and the AJAX response is missing—usually stem from a fundamental mismatch between how the client sends data and how the server expects to receive it.

The primary culprit in your scenario is the handling of FormData objects within the jQuery AJAX request. You are correctly creating a FormData instance and appending both the file object and the serialized form fields:

var fileToUpload = inputFile[0].files[0];
var other_data = $('#frm_imageuupload').serializeArray();
var formdata = new FormData();

formdata.append(fileToUpload);
// Append individual fields individually to ensure they are part of the multipart stream
for (var i = 0; i < other_data.length; i++) {
    formdata.append(other_data[i].name, other_data[i].value);
}

However, there is a critical configuration error in your AJAX settings. You have set processData: false and contentType: false, which is correct for sending raw multipart data. The issue arises because you are appending the entire serialized array to the FormData object but then trying to access those specific fields by their HTML IDs or names in the controller without ensuring they were actually passed through the POST payload correctly.

In your controller, you are retrieving values using $_POST logic via $this->input->post(). When using FormData, the data is sent as a multipart stream. While serializeArray() works for standard JSON submissions, appending it to FormData requires careful handling of the field names. Ensure that the names in the <input> tags (e.g., name="selectmenuid") exactly match what you are reading in the controller ($this->input->post('selectmenuid')).

A frequent pitfall occurs when the form contains fields that are not intended for file uploads but are being serialized alongside them. If any field is missing its name attribute, or if the enctype="multipart/form-data" is missing from the <form> tag (which you have correctly included), the browser will attempt a standard POST, causing the AJAX call to fail silently or behave unexpectedly.

Furthermore, the controller logic needs to verify that the file upload itself succeeded before attempting database operations. Your current code checks if($this->upload->do_upload()), which is good practice. However, if the upload fails due to permissions on the ./upload directory or incorrect allowed_types, the script stops and no response is sent back to the AJAX success handler.

To ensure a robust user experience, you should explicitly check the upload data in the controller and return a structured JSON response rather than echoing "true". This prevents confusion when parsing the result:

public function do_upload() {
    $config['upload_path'] = './upload';
    $config['allowed_types'] = 'gif|jpg|png';
    $this->load->library('upload', $config);

    if ($this->upload->do_upload('file')) { // Ensure the input name matches exactly
        $data = array('upload_data' => $this->upload->data());
        
        // Retrieve form data safely
        $menu_id = $this->input->post('selectmenuid');
        $submenu_id = $this->input->post('selectsubmenu');
        $imagetitle = $this->input->post('imagetitle');
        $imgpath = $data['upload_data']['file_name'];

        // Validate database insertion
        if ($this->Admin_model->save_imagepath(array(
            'menu_id' => $menu_id,
            'submenu_id' => $submenu_id,
            'imagetitle' => $imagetitle,
            'imgpath' => $imgpath
        ))) {
            echo json_encode(['status' => 'success', 'message' => 'Upload complete']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Database insert failed']);
        }
    } else {
        $error = array('error' => $this->upload->display_errors());
        echo json_encode(['status' => 'error', 'message' => implode(', ', $error)]);
    }
}

In the AJAX success handler, check for this JSON structure instead of comparing against the string 'true'. This approach handles edge cases like empty selects or invalid file types more gracefully. If the upload directory permissions are incorrect on the server, the do_upload() method will return false, and you can log the specific error messages provided by CodeIgniter's upload library to debug further.

For developers looking for more modern PHP frameworks that handle these file operations with built-in routing and validation out of the box, platforms like Laravel offer streamlined methods for handling multipart requests without manual configuration. For instance, https://laravelcompany.com provides resources on how similar upload flows are implemented in newer ecosystems, though CodeIgniter remains a solid choice when leveraging its existing libraries effectively.

By aligning the client-side FormData construction with the server-side input retrieval and ensuring proper error handling, you eliminate the redirection issues and ensure that data persists correctly in your database.

Our network