How to upload file using ajax in codeigniter

In the last tutorial of file upload I have explained you Upload multiple files using codeigniter . In this tutorial I will explain you how to upload file using ajax in codeigniter. I have seen many user get difficulties to upload while using ajax to upload file. To upload file using ajax you just need to add some code inside your Ajax. Now create a file name Test.php inside the view folder and copy and paste the below code.

<script src=""></script>
<script type="text/javascript">
function sendData()
    var data = new FormData($('#posting_comment')[0]);
               url:"<?php echo site_url('Test/fileUpload');?>",
               mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
<form name="posting_comment" id="posting_comment" >
      <input id="file_upload" name="attachment_file" class="file_upload_icon" type="file"/>
      <input type="button" class="post postbtn" style="border: none;outline:none;" value="Post" onclick = "return sendData()"/>


In the above code we will get the all form data in the data variable and we have used onclick function inside button to run the function sendData()     and call the controller in ajax url. Do not forget to add mimeType: “multipart/form-data” is very important for file upload.

Now create the controller name Test.php   inside the controller folder and copy and paste the following code. In the code we will autoload the view file and will make a function fileUpload() that will be used to get the file name and uplaod the file in the folder.

defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends CI_Controller {
	public function __construct() {
	public function index()
       public function fileUpload()
              $output_dir = "upload/";
              $fileName = $_FILES["attachment_file"]["name"];
		echo "File uploaded successfully";

Hope this tutorial how to upload file using ajax in codeigniter will help you.
Read this for Upload multiple files using codeigniter

  • Tarun Pawar

    if ($(“#donation_confirm”).valid()) {
    var connetionID = $(“#connetionID”).val();
    var donerID = $(“#donerID”).val();
    var message = $(“#message”).val();
    var user_profile = $(“#user_profile”).val();
    var image = inputFile[0].files[0];
    //var formData = new FormData( $(“#donation_confirm”)[0] );
    var file = new FormData($(‘#donation_confirm’)[0]);

    type: “POST”,
    url: “”,
    data: {connetionID: connetionID, donerID: donerID, message: message, user_profile: user_profile,file: file},
    cache: false,
    contentType: false,
    processData: false,

    success: function(result){

    alert(‘Thank you..!!’);



    it is give ReferenceError: inputFile is not defined