Jwags
Jwags

Reputation: 502

CodeIgniter AJAX Receiving error on file upload

I have been stuck on this problem for quite a while and decided to seek help. It does not seem like an issue that should be causing me so much frustration but I just cannot figure this out.

I am trying to upload a file from a form using CodeIgniter and AJAX. Any suggestions would be great. Thanks!

View:

<form method='post' enctype='multipart/form-data'>
    <label>Name</label>
    <input type='text' id='ImageName' class='form-control' /><br />
    <label>Image</label>
    <input type='file' name='userfile' id='userfile' />
    <button type='button' class='btn btn-success extend-btn' id='UploadSaveButton'>Add Materials</button>
</form>

JS

$(document.body).on('click', '#UploadSaveButton', function(){
    var Name = $("#ImageName").val();
    var Image = new FormData($("#userfile").val());
    $.ajax({
        url: '/Store/SaveImage',
        type: 'POST',
        processData: false,
        contentType: false,
        fileElementId: 'userfile',
        dataType: 'json',
        data: {Name:Name, Image:Image},
        success:function(response){
            var data = JSON.parse(response);
            if(data && data.error_message && data.error_message!="") {
                $("#UploadError").html(data.error_message);
            } else {
                //success
            }
        },
        error:function(){
            $("#UploadError").html("An error occured. Try again later.");
        }
    });
});

Controller

public function SaveImage()
{
    $config['upload_path']   = base_url().'uploads/PrimaryImages/'; 
    $config['allowed_types'] = 'jpeg|jpg|png'; 
    $config['max_size']      = 1024; 
    $config['max_width']     = 5000; 
    $config['max_height']    = 5000;  
    $this->load->library('upload', $config);

    if(!$this->upload->do_upload('userfile')) {
        $data = array(
            'error_message' => $this->upload->display_errors()
        );
    } else { 
        $data['upload_data'] = $this->upload->data();
    }
    $this->output->set_output(json_encode ($data));
}

No matter what I do, the Json response is always "You did not select a file to upload."

Upvotes: 0

Views: 257

Answers (2)

Jwags
Jwags

Reputation: 502

Upon further research I discovered that images cannot be sent accross an AJAX call without using iFrame. I honestly don't believe that and I am convinced there is a way. Anyway, with no avail, I resulted to a plugin. http://filer.grandesign.md/

Upvotes: 0

Pradeep
Pradeep

Reputation: 9717

keeping it very simple :

upload form :

  <form class="ui form" method="post" id="uploadForm" enctype="multipart/form-data">
       <div class="ui form">
           <div class="field required ">
           <label>Bonus Amount</label>
           <input name="userfile" id="userfile" placeholder="Bonus Amount" type="file" ></div>
           <button name="action" class="ui button" id="upload" value="Upload">Upload Image</button>
     </div>
 </form>

Your ajax :

<script >
  $(document).ready(function(e) {
     $('#upload').on('click' , function () {
       $.ajax({
        url : '<?php echo base_url().'admin/uploadImage' ?>',
        type : 'post',
        data: $('#uploadForm').serialize(), 
        success : function(response) {
            console.log(response);
        }   
    });});
 });
 </script>

Controller :

public function uploadImage() {

    if($this->input->post('action') == 'Upload') {
        $data = array();
        $config['upload_path'] = APPPATH.'uploads'.DIRECTORY_SEPARATOR;
        $config['allowed_types'] = '*'; 
        $config['max_size']      = 1024; 
        $config['max_width']     = 5000; 
        $config['max_height']    = 5000;  
        print_r($config);
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userfile')) {
           $data = array('error_message' => $this->upload->display_errors());
        } else { 
           $data['upload_data'] = $this->upload->data();
       }
       print_r($data);
       die;
    }

}

Upvotes: 2

Related Questions