0

I have been trying to upload an image with AJAX but somehow it's not working. CodeIgniter always throwing 'You have not selected any file'. Thanks in advance.

Here's my Controller -

class Upload extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('upload/upload');
    }

    public function upload_file() {
        $config['upload_path'] = './uploads/Ajax/';
        $config['allowed_types'] = 'gif|jpg|png|doc|txt';
        $config['max_size'] = 1024 * 8;

        $this->load->library('upload', $config);
        $title=$this->input->post('title');

        if (!$this->upload->do_upload('userfile')) {
            echo $this->upload->display_errors()."<br>".$title;
        }
        else {
            $data = $this->upload->data();
            echo $data['file_name']." uploaded successfully";
        }
    }
}

/* end of file */

And here's the view

<!DOCTYPE HTML>
<html>
    <head>
        <title>AJAX File Upload</title>
        <script src="<?php echo base_url(); ?>assets/js/jquery-1.11.3.js">    </script>
        <script src="<?php echo base_url(); ?>assets/js/AjaxFileUpload.js">    </script>
        <script>
            $(document).ready(function() {
                $('#upload-form').submit(function(e) {
                    e.preventDefault();
                    if (typeof FormData !== 'undefined') {
                        $.ajax({
                            url     :   '<?php echo base_url(); ?>upload/upload/upload_file',
                            type    :   'POST',
                            data    :   FormData,
                            beforeSend: function () {
                                $("#result").html("Uploading, please wait....");
                            },
                            error: function () {
                                alert("ERROR in upload");
                            },
                            success :   function(data) {
                                $('#result').html(data)
                            }
                        });
                    }
                    else {
                        alert("Your browser doesn't support FormData API!");
                    }
                });
            });
        </script>
    </head>

<body>
    <h1>Upload File</h1>
    <form method="post" action="" id="upload-form" enctype="multipart/form-data" accept-charset="utf-8">
        <p>
            <label for="title">Title</label>
            <input type="text" name="title" id="title" value="" autocomplete="off">
        </p>
        <p>
            <label for="userfile">File</label>
            <input type="file" name="userfile" id="userfile">
        </p>
        <input type="submit" name="submit" id="submit">
    </form>

    <h2>Result</h2>
    <span id="result"></span>
</body>

I have tested in Firefox 43, IE11 & Chrome 43

5 Answers 5

1
<script>
        $(document).ready(function() {
            $('#upload-form').submit(function(e) {
                e.preventDefault();
                if (typeof FormData !== 'undefined') {
                    $.ajax({
                        url     :   '<?php echo base_url(); ?>upload/upload/upload_file',
                        type    :   'POST',
                         secureuri      :false,
                       fileElementId    :'userfile',
                        data    :   FormData,
                        beforeSend: function () {
                            $("#result").html("Uploading, please wait....");
                        },
                        error: function () {
                            alert("ERROR in upload");
                        },
                        success :   function(data) {
                            $('#result').html(data)
                        }
                    });
                }
                else {
                    alert("Your browser doesn't support FormData API!");
                }
            });
        });
    </script>
Sign up to request clarification or add additional context in comments.

Comments

1

You need to add xhr function in ajax request

$(document).on('submit','#form_id',function(){
   var formData = new FormData(this);
   $.ajax({
        type:'POST',
        xhr: function() {
            var xhrobj = $.ajaxSettings.xhr();            
            return xhrobj;
        },
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
            console.log(data);
        }
    });
});

Comments

0

you can use

$(document).on('submit','#form_id',function(){
   var formData = new FormData(this);
   $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            console.log("success");
            console.log(data);
        },
        error: function(data){
            console.log("error");
            console.log(data);
        }
    });
});

no plugin required for this, for easiness you can use ajaxForm jquery plugin and just use

$('#form-id').ajaxSubmit({
   // same config as ajax call but dont use data option right here
}); 

have a look on http://malsup.com/jquery/form/ to for more information about plugin

Comments

0

Use this

$("#upload-form").on('submit' ,function(){
    var form = $(this);
    $.ajax({
        url: form.attr('action'),
        data: new FormData(form[0]),
        dataType: 'json',
        method: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){


        }
    });
});

Comments

0

Use $.ajaxFileUpload instead $.ajax, this should work, if not please let me see your AjaxFileUpload.js

$(document).ready(function() {
                $('#upload-form').submit(function(e) {
                    e.preventDefault();
                    if (typeof FormData !== 'undefined') {

                       $.ajaxFileUpload({ 
                        url             :'./upload/upload_file/',                  
                        fileElementId   : 'userfile', //  your input file ID
                        dataType        : 'json',
                        // 
                        data            : {
                            'title'             : $('#title').val() // parse title input data
                        },
                            beforeSend: function () {
                                $("#result").html("Uploading, please wait....");
                            },
                            error: function () {
                                alert("ERROR in upload");
                            },
                            success :   function(data) {
                                $('#result').html(data)
                            }
                        });
                    }
                    else {
                        alert("Your browser doesn't support FormData API!");
                    }
                });
            });

2 Comments

Replace your ajaxFileUpload with this [ajaxFileUpload.js] dropbox.com/s/b0a6lb8mtpxkp4w/ajaxFileUpload.js?dl=0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.